Convert JSON objects to dictionary in python

I have a data string mainly containing objects with objects.

{"id":"XXXX", "name": "xyz", "user" : { "id": "XXXX", "username":"XYZ", group:{"id": "XXXX"}}}. You can check this format using "http://chris.photobooks.com/json/default.html" site. 

It is not my requirement to convert this to JSON objects as a dictionary. I tried below.

 import json JSON_Datalist = '{"id":"XXXX", "name": "xyz", "user" : { "id": "XXXX", "username":"XYZ", group:{"id": "XXXX"}}}' the_dict = json.loads(JSON_DataList) 

but the_dict gives only the values โ€‹โ€‹of the left side, does not have the correct values โ€‹โ€‹...

Similarly, if the string has a format.

 "[{"sample": false, "radop": null, "view": true, "Example1": null}, {"noMarket": false, "Example2": null}]" 

and following the same code.

 JSON_Datalist = '[{"sample": false, "radop": null, "view": true, "Example1": null}, {"noMarket": false, "Example2": null}]' the_dict = json.loads(JSON_DataList) 

it gives a dictionary of length 2, and this is what was expected ...

Can someone help me in the first case, how can I get the dictionary ...

+6
source share
3 answers

In the first example, I found two errors:

  • You have group in your string (Json) version of your dict. This should be a "group" (with quotes).
  • You made a mistake in your variable; JSON_Datalist โ‰  JSON_Datalist (lower case versus capital L).

After fixing both problems, I had no more problems:

 >>> JSON_Datalist = '{"id":"XXXX", "name": "xyz", "user" : { "id": "XXXX", "username":"XYZ", "group":{"id": "XXXX"}}}' >>> the_dict = json.loads(JSON_Datalist) >>> the_dict {u'user': {u'username': u'XYZ', u'group': {u'id': u'XXXX'}, u'id': u'XXXX'}, u'id': u'XXXX', u'name': u'xyz'} 
+5
source

after fixing the problem group should be a "group", the code below may correspond to your requirement

 json_data={"id":"XXXX", "name": "xyz", "user" : { "id": "XXXX", "username":"XYZ", "group":{"id": "XXXX"}}} data = json.dumps(json_data) json_to_python = json.loads(data) print (json_to_python) {'id': 'XXXX', 'name': 'xyz', 'user': {'id': 'XXXX', 'username': 'XYZ', 'group': {'id': 'XXXX'}}} 
+1
source

I figured out how to generate the_dict['user']['group']['id'] dynamically through a Python expression eval .

Keys is the user input, divided by : Example: user:group:id .

CODE:

 RefCount = 0 RespDict = json.loads(JSON_Datalist.content) #convert strings to Java object using JSON SplitKeys = Keys.split(":") KeyCount = len(SplitKeys) CommandText = "RespDict" #To setup command line based on keys information while (RefCount <KeyCount): CommandText = CommandText+"['"+SplitKeys[RefCount]+"']" RefCount = RefCount + 1 print CommandText print eval(CommandText) #Final key value 
0
source

Source: https://habr.com/ru/post/954996/


All Articles