我有一个包含多个JSON
文件的目录。每个JSON
文件都有一个JSON
结构(每个结构中有3个字典元素)。我想读取每个JSON
文件,并将字典附加到一个dictionary
中-一个主dictionary
,其中包含所有字典。这是我的代码:
def json_read:
pathToDir = '/path/to/directory'
json_mstr = {}
for file_name in [file for file in os.listdir(pathToDir) if file.endswith('.json')]:
with open(pathToDir + file_name) as input_file:
print(file_name)
json_str = json.load(input_file)
json_mstr.update(json_str)
print(len(json_mstr))
return json_mstr
当我打印长度时,我只看到3
作为最终主dictionary
的长度,并且只看到主dictionary
中最后一个JSON
文件的字典内容。不知道为什么update()
在每次读取文件后都会重置字典?
注意:每个文件中JSON
的示例结构如下:
{
"resourceType": "Single",
"type": "transaction",
"entry": [
{
"fullUrl": "urn:uuid",
"resource": {
"resourceType": "Employee",
"id": "4cb1a87c",
"text": {
"status": "generated",
"div": "generated"
},
"extension": [],
"identifier": [
{
"system": "https://github.com",
"value": "43f123441901"
}
],
"name": [
{
"use": "official",
"family": "Shields52",
"given": [
"Aaro97"
],
"prefix": [
"Mr."
]
}
],
"maritalStatus": {
"coding": [
{
"system": "MaritalStatus",
"code": "M",
"display": "M"
}
],
"text": "M"
},
"multipleBirthBoolean": false
},
"request": {
"method": "POST",
"url": "User"
}
},
{
"fullUrl": "f411764e1f01",
"resource": {
"resourceType": "Claim",
"id": "411764e1f01",
"status": "active",
"type": {
"coding": [
{
"system": "type",
"code": "Company"
}
]
},
"use": "claim",
"employee": {
"reference": "1141dfb308"
},
"billablePeriod": {
"start": "2009-12-24T16:42:36-05:00",
"end": "2009-12-24T16:57:36-05:00"
},
"created": "2009-12-24T16:57:36-05:00",
"provider": {
"reference": "7e31e2b3feb"
},
"priority": {
"coding": [
{
"system": "Employee",
"code": "normal"
}
]
},
"procedure": [
{
"sequence": 1,
"procedureReference": {
"reference": "58f373a0a0e"
}
}
],
"insurance": [
{
"sequence": 1,
"focal": true,
"coverage": {
"display": "Employer"
}
}
],
"item": [
{
"sequence": 1,
"productOrService": {
"coding": [
{
"system": "http://comp1.info/",
"code": "1349003",
"display": "check up"
}
],
"text": "check up"
},
"encounter": [
{
"reference": "bc0a5705f6"
}
]
},
{
"sequence": 2,
"procedureSequence": [
1
],
"productOrService": {
"coding": [
{
"system": "http://comp.info",
"code": "421000124101",
"display": "Documentation"
}
],
"text": "Documentation"
},
"net": {
"value": 116.60,
"currency": "USD"
}
}
],
"total": {
"value": 163.7,
"currency": "USD"
}
},
"request": {
"method": "POST",
"url": "Employee"
}
}
]
}
1条答案
按热度按时间vptzau2j1#
字典是一个键值Map。
update
将覆盖相同的键。如果你想有3个字典里面的一个,给予他们一些关键字,例如文件名: