Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python合并JSON记录_Python_Json - Fatal编程技术网

使用Python合并JSON记录

使用Python合并JSON记录,python,json,Python,Json,我有一个巨大的json文件,如下所示 {"id": "KA88457","name": "Steven", "phone":"+6590876589"}, {"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"} 我需要将两者合并,并获得所需的结果 {"id": "KA88457", "name": "Steven", "phone":"+6590876589", "fax":["+6563323

我有一个巨大的json文件,如下所示

{"id": "KA88457","name": "Steven", "phone":"+6590876589"},
{"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}
我需要将两者合并,并获得所需的结果

{"id": "KA88457",
 "name": "Steven", 
 "phone":"+6590876589", 
 "fax":["+6563323248"], 
 "email":"steve@alexandra.com"}

我在网上查过了,但在python中只能找到两个json文件的合并。请您帮助使用python合并这些类型的记录。

假设您知道如何将字符串从json转换为python字典对象,请参阅json模块,您可以按照描述的方式“合并”它们,如下所示:

objOne = {"id": "KA88457","name": "Steven", "phone":"+6590876589"}
objTwo = {"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}

for key in objOne:
    objTwo[key] = objOne[key]

这将获取objOne的所有属性并将它们添加到objTwo。

Python字典有一个.update方法,该方法也可用于您的情况。它用于更新原始dict,以包括第二个dict的更改或添加

first_dict={"id": "KA88457","name": "Steven", "phone":"+6590876589"}
second_dict={"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}
first_dict.update(second_dict)
print(first_dict)
输出:

{'id': 'KA88457', 'name': 'Steven', 'phone': '+6590876589', 'fax': ['+6563323248'], 'email': 'steve@alexandra.com'}

你的意思是,我必须将它们转换成字符串,然后使用json模块merge?而且文件大小太大。我是python新手。所以,我对如何继续感到困惑。上面已经是一本字典了,对吗?如果我错了,请纠正我。那些是字典里的东西。但是如果你从一个文件中读入它们,它们会以字符串的形式出现,你需要将它们解析成一个dictionary对象。我正在从文件中读取它们。这意味着我需要解析它们。我试试看。谢谢。但我有一个疑问。1.文件很大。我怎样才能知道第一个dict必须附加第二个dict?可能是我使用循环来检查它是否有相似的id,它必须附加和删除重复项。还有其他解决办法吗?2.如何将这些字典分配给新变量,如first_dict和second_dict?对不起,我要问一些愚蠢的问题