13

我基本上有一串数据,其中对象中有一个对象..

{"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.

不,我的要求是将其转换为 JSON 对象作为字典。我尝试过以下方式

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

但是 the_dict 只给出左边的值,没有右边的值......

以同样的方式,如果字符串具有格式..

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

并遵循相同的代码。

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

the_dict = json.loads(JSON_DataList)

它给出了长度为 2 的字典,这是预期的......

任何人都可以在第一种情况下帮助我如何获得字典...

4

3 回答 3

8

我在您的第一个示例中发现了两个错误:

  1. 您的字典中有一个group字符串化(Json)版本。这应该是"group"(带引号)。
  2. 你拼错了你的变量;JSON_DatalistJSON_DataList(小写与大写 L)。

修复两者后,我再也没有问题了:

>>> 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'}
于 2013-10-01T08:01:47.140 回答
4

修复后问题组应该是“组”,下面的代码可以满足您的要求

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'}}}
于 2017-05-24T07:40:37.863 回答
0

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

Keys is the input from the user, separated 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
于 2013-10-09T13:40:41.670 回答