我正在尝试按如下方式创建嵌套的Json结构:
示例Json:
{
"id" : "de",
"Key" : "1234567",
"from" : "test@test.com",
"expires" : "2018-04-25 18:45:48.3166159",
"command" : "method.exec",
"params" : {
"method" : "cmd",
"Key" : "default",
"params" : {
"command" : "testing 23"
}
}
我试图从OrderedDict中做到这一点。我不确定构造OrderedDict的正确方法,以便生成正确的Json。
Python代码:
json_payload = OrderedDict(
[('id', id),
('Key', keystore),
('from', 'test@test.com'),
('expires', expires),
('command', 'method.exec')]
# What goes here for the params section??
)
print json.dumps(json_payload, indent=4, default=str)
答案 0 :(得分:1)
您在JSON数据末尾错过了}
。
import json
import collections
data = {
"id" : "de",
"Key" : "1234567",
"from" : "test@test.com",
"expires" : "2018-04-25 18:45:48.3166159",
"command" : "method.exec",
"params" : {
"method" : "cmd",
"Key" : "default",
"params" : {
"command" : "testing 23"
}
}}
data_str = json.dumps(data)
result = json.loads(data_str, object_pairs_hook=collections.OrderedDict)
print(result)
输出:
OrderedDict(
[
('id', 'de'),
('Key', '1234567'),
('from', 'test@test.com'),
('expires', '2018-04-25 18:45:48.3166159'),
('command', 'method.exec'),
('params',
OrderedDict(
[
('method', 'cmd'),
('Key', 'default'),
('params',
OrderedDict(
[
('command', 'testing 23')
]
)
)
]
)
)
]
)
答案 1 :(得分:0)
一些事情。 id
是关键字。您只需将字典作为参数传递即可。
ids = "de"
keystore = "1234567"
expires = "2018-04-25 18:45:48.3166159"
pdict = {
"method" : "cmd",
"Key" : "default",
"params" : {
"command" : "testing 23"
}
}
json_payload = OrderedDict(
[('id', id),
('Key', keystore),
('from', 'test@test.com'),
('expires', expires),
('command', 'method.exec'),
('params',pdict )
]
)
print(json.dumps(json_payload, indent=4, default=str))
答案 2 :(得分:0)
使用@ haifzhan的输出作为输入,完全按照要求提供。
payload = OrderedDict(
[
('id', 'de'),
('Key', '1234567'),
('from', 'test@test.com'),
('expires', '2018-04-25 18:45:48.3166159'),
('command', 'method.exec'),
('params',
OrderedDict(
[
('method', 'cmd'),
('Key', 'default'),
('params',
OrderedDict(
[
('command', 'testing 23')
]
)
)
]
)
)
]
)
print json.dumps(json_payload, indent=4, default=str)