[英]Nesting with JSON Library in Python
我正在努力让我的Python代码能够为我的JSON消息输出正确的嵌套和格式。 我的问题是我无法像给出样本JSON那样将对象嵌套在JSON中,因为这只是源系统将接受它的方式。 我已经在线阅读了文档和其他教程等,但我发现没有任何内容可以解决这个问题。
以下是我必须使用的示例JSON,其中包含正确的格式:
{"messageId": "ID,"messageType": "Type","createdDateTime": "2019-01-01T10:10:10Z","recordOne": [{"dataItemOne": "E123345","dataItemTwo": "2019-01-01T12:12:12Z","attributesRecord": {"attributesOne": 22,"attributesTwo": 24,},"recordTwo": {"dataItemOne": "L22","dataItemTwo": "EL","dataItemThree": "ADDFES334S",},"recordThree": [{"itemOne": "P44587"}]}]}
这是我的代码
import datetime
import json
datetime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
data = {'messageId': 'ID',
'messageType': 'Type',
'createdDateTime': datetime}
data1 = {'recordOne': []}
data1['recordOne'].append({
'dataItemOne': 'E123345',
'dataItemTwo': datetime,
})
datas = [data, data1]
with open('mata.json', 'w') as outfile:
data = json.dumps(data)
json.dump(datas, outfile)
这给了我这种类型的JSON:
[{"messageId": "ID","messageType": "Type","createdDateTime": "2019-03-14T20:31:55Z"}, {"recordOne": [{"dataItemOne": "E123345","dataItemTwo": "2019-03-14T20:31:55Z"}]}]
我的主要问题是我无法将文件输出到:
任何人都可以帮助我,请原谅我,我是一个菜鸟?
注意 - 为了解决这个问题,我创建了一个单独的脚本,打印出正确的嵌套和格式,但是我很难被告知要使用该库,我知道库有限制并且不确定这是否是其中之一。
看看下面的代码片段
import datetime
import json
dt = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
data = {'messageId': 'ID',
'messageType': 'Type',
'createdDateTime': dt}
data['recordOne'] = [{
'dataItemOne': 'E123345',
'dataItemTwo': dt
}]
# since recordOne contains a list, we use [0] to paste stuff inside it
data['recordOne'][0]['attributesRecord'] = {
'attributesOne': 22,
'attributesTwo': 24
}
data['recordTwo'] = {
...
}
# and so on and so forth
with open('mata.json', 'w') as outfile:
json.dump(data, outfile)
data['recordOne']
,主要的一点是,如果你想在字典中添加一些内容,你可以通过编写data['recordOne']
和data['recordOne'][0]['attributesRecord']
创建一个新密钥。 ,同时这样做,你也可以为它分配你想要的值。
如果你想继续嵌套,那就继续增加键的级别。 请记住,如果要将字典放在列表中,则必须使用各自的索引(例如[0]
)访问列表中的键值对。
由于你的一些词典也必须在列表中,所以我会这样添加它们(参见第一个data['recordOne']
)。
最后, json.dumps()
用于创建字符串,而json.dump()
用于写入文件。 所以使用它。 希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.