繁体   English   中英

如何合并 2 个 JSON 数组文件?

[英]How to merge 2 JSON array files?

我从 web 刮取了多个带有 JSON arrays 的文件。 它们看起来都像这样:

db_1.txt
[
{"title": "Title1", "price" : 21.37},
{"title": "Title2", "price" : 32.10},
{"title": "Title3", "price" : 221.67}
]

db_2.txt
[
{"title": "Title4", "price" : 121.37},
{"title": "Title5", "price" : 232.10}
]

如何将这些文件合并在一起,同时保持相同的 JSON 数组格式? 我显然尝试在需要的地方删除或添加“,”,但这可能不是那么优雅和 memory 有效的方式。

You could use the loads function of the json module that Python provides out of the box in order to read and process the json structures inside these .txt files and then append them to a final list in order to use it any way you want:

import json

result = []
textFiles = ['db_1.txt', 'db_2.txt']
for textFile in textFiles:
    with open(textFile, 'r') as file_1:
        data = json.loads(file_1.read())
        result.extend(data)

print(result)

这将打印:

[{'title': 'Title1', 'price': 21.37}, {'title': 'Title2', 'price': 32.1}, {'title': 'Title3', 'price': 221.67}, {'title': 'Title4', 'price': 121.37}, {'title': 'Title5', 'price': 232.1}]

你可以这样做:

db_1.txt

{
    merged_files:[
          "tile1":"title2","price"
          "tilte3":"title4","price"
      ]
}


]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM