我是Python新手,我正在玩JSON数据.我想从文件中检索JSON数据,并在"动态"中向该数据添加JSON键值.
也就是说,我json_file包含JSON数据,如下所示:
{"key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
Run Code Online (Sandbox Code Playgroud)
我想将"ADDED_KEY": "ADDED_VALUE"键值部分添加到上面的数据中,以便在我的脚本中使用以下JSON:
{"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
Run Code Online (Sandbox Code Playgroud)
我想写一些像以下内容,以完成上述事情:
import json
json_data = open(json_file)
json_decoded = json.load(json_data)
# What I have to make here?!
json_data.close()
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 19
你的json_decoded对象是一个Python字典; 您只需将密钥添加到该密钥,然后重新编码并重写该文件:
import json
with open(json_file) as json_file:
json_decoded = json.load(json_file)
json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
with open(json_file, 'w') as json_file:
json.dump(json_decoded, json_file)
Run Code Online (Sandbox Code Playgroud)
我在这里使用了打开的文件对象作为上下文管理器(使用with语句),因此Python在完成后会自动关闭文件.
你可以做
json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
Run Code Online (Sandbox Code Playgroud)
或者
json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
Run Code Online (Sandbox Code Playgroud)
如果您想添加多个键/值对,这很有效。
当然,您可能想先检查 ADDED_KEY 是否存在 - 取决于您的需要。
而且我假设您可能希望将该数据保存回文件
json.dump(json_decoded, open(json_file,'w'))
Run Code Online (Sandbox Code Playgroud)
小智 5
Json从json.loads()返回的行为就像本机python列表/词典一样:
import json
with open("your_json_file.txt", 'r') as f:
data = json.loads(f.read()) #data becomes a dictionary
#do things with data here
data['ADDED_KEY'] = 'ADDED_VALUE'
#and then just write the data back on the file
with open("your_json_file.txt", 'w') as f:
f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
#I added some options for pretty printing, play around with them!
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看官方文档
| 归档时间: |
|
| 查看次数: |
43578 次 |
| 最近记录: |