簡體   English   中英

如何合並來自文件的兩個json對象

[英]How to merge two json objects coming from a file

我有兩個來自文件的 json 對象。 這兩個對象創造了一個記錄。 它們的長度不同。 我正在使用 pandas.read_json(),但沒有用。 這是一個例子:

輸入:

{"a":1,"b":2,"c":3}{"x":[100],"y":"123"}

預期輸出:

{
   "a":1,
   "b":2,
   "c":3,
   "x":[100],
   "y":"123"
}

IIUC,您想讀取兩個 JSON 並從中創建一個新的 JSON。

import json

new_json = {}
for json_file in ['js1.json', 'js2.json']:
    with open(json_file) as f:
        d = json.load(f)
        new_json.update(d)
        
print(new_json)
# {'a': 1, 'b': 2, 'c': 3, 'x': [100], 'y': '123'}

# create a new json that contains two old json
res = json.dumps(new_json)

更新您可以使用ast.literal_eval ,如果兩個 JSON 在一個文件中。

import json
import ast

# jss.json -> {"a":1,"b":2,"c":3}{"x":[100],"y":"123"}

new_json = {}
for json_file in ['jss.json']:
    with open(json_file) as f:
        jsons = f.read()
        for js in jsons.split('}')[:-1]:
            st = js+'}'
            d = ast.literal_eval(st)
            new_json.update(d)
        
print(new_json)
# {'a': 1, 'b': 2, 'c': 3, 'x': [100], 'y': '123'}

# create a new json that contains two old json
res = json.dumps(new_json)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM