Python: Transform [str] type Json data into [dict] type
Question: 
    import json
    
    data1 = {'b': 789, 'c': 456, 'a': 123}
    
    encode_line = json.dumps(data1)
    decode_json = json.loads(encode_line)
    
    print type(encode_line)
    print type(decode_line)
    

The type(decode_line) is [dict], but when we save data1 into an txt file, and
read it using below script:

    
    
    file = open('test.txt','r')
    for line in file:
        encode_line = json.dumps(line)
        decode_line = json.loads(encode_line)
    
        print type(encode_line)
        print type(decode_line)
    

Now, the type(decode_line) is [unicode]. why ?

I want to read data from txt file and then retrieve info from dict type. How
should I do ?

Thanks!


Answer: **Hi!**

This should do the trick:

    
    
    import json;
    
    def readJSON(filename):
        "Reads JSON file, returns correspoding dict.";
        with open(filename) as f:
            return json.loads(f.read());
    

**How it works:**

`json.dumps(.)` converts Python dict to JSON string.  
`json.loads(.)` converts JSON string to Python dict.

In Your code, you call `json.dumps(line)`, but `line` is a string!  
For `json.dumps(.)` to work correctly, you must supply a Python dict, not
string.

In this context, `dumps` is read as "dump-s", "s" for string. It takes a dict
and dumps (i.e. returns) it's string representation. Similarly, `loads` is
read as "load-s". It loads (i.e. accepts) a JSON string and returns it's
corresponding dict.

**Hope this helps.**

