简体   繁体   English

如何通过python在json中写入或附加对象的特定键/值

[英]How to write or append at a specific key/value of an object in json via python

The question is very self explanatory.这个问题是不言自明的。 I need to write or append at a specific key/value of an object in json via python.我需要通过 python 在 json 中的对象的特定键/值上写入或附加。

I'm not sure how to do it because I'm not good with JSON but here is an example of how I tried to do it (I know it is wrong).我不知道该怎么做,因为我不擅长 JSON,但这里有一个我尝试这样做的例子(我知道这是错误的)。

with open('info.json', 'a') as f:
    json.dumps(data, ['key1'])

this is the json file:这是 json 文件:

{"key0":"xxxxx@gmail.com","key1":"12345678"}

A typical usage pattern for JSONs in Python is to load the JSON object into Python, edit that object, and then write the resulting object back out to file. Python中 JSON 的典型使用模式是将 JSON 对象加载到 Python 中,编辑该对象,然后将生成的对象写回文件。

import json

with open('info.json', 'r') as infile:
    my_data = json.load(infile)
    
my_data['key1'] = my_data['key1'] + 'random string'
# perform other alterations to my_data here, as appropriate ...

with open('scratch.json', 'w') as outfile:
    json.dump(my_data, outfile)

Contents of 'info.json' are now 'info.json' 的内容现在是

{"key0": "xxxxx@gmail.com", "key1": "12345678random string"}

The key operations were json.load(fp) , which deserialized the file into a Python object in memory, and json.dump(obj, fp) , which reserialized the edited object to the file being written out.关键操作是json.load(fp) ,它将文件反序列化为内存中的 Python 对象,以及json.dump(obj, fp) ,它将编辑后的对象重新序列化为正在写出的文件。

This may be unsuitable if you're editing very large JSON objects and cannot easily pull the entire object into memory at once, but if you're just trying to learn the basics of Python's JSON library it should help you get started.如果您正在编辑非常大的 JSON 对象并且无法轻松地一次将整个对象拉入内存,这可能不合适,但如果您只是想学习 Python JSON 库的基础知识,它应该可以帮助您入门。

An example for appending data to a json file using json library:使用json库将数据附加到 json 文件的示例:

import json

raw =  '{ "color": "green",  "type": "car" }'
data_to_add = { "gear": "manual" }  
parsed = json.loads(raw) 
parsed.update(data_to_add) 

You can then save your changes with json.dumps .然后您可以使用json.dumps保存您的更改。

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

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