简体   繁体   English

向现有 JSON 文件添加值

[英]Add value to existing JSON file

I would like to define the following simple function:我想定义以下简单函数:

def add_to_json(self, json, node_name, value_name, value):
    json[node_name][value_name] = value

where json is a JSON file to modify, so it would be called like this:其中json是一个要修改的 JSON 文件,所以它会被这样调用:

jsonToModify = json.load(open(path_to_jason_file)) # path is of the type: "C:/Users/path/to/file.json"
self.add_to_json(jsonToModify, "NodeName", "ValueName", self.stuff)

I have searched how to use the json.load() function, but I get this error if I give it a string:我已经搜索了如何使用json.load()函数,但是如果我给它一个字符串,我会得到这个错误:

在此处输入图片说明

I am not sure on what to give to json.load ;我不确定要给json.load什么; how can I give the path to my file as an input?如何将文件路径作为输入?

Here is a demo of reading data from an existing json file into a Python object (a dict), adding a value to the dict and writing the updated dict as json back to the file.这是一个从现有的 json 文件中读取数据到 Python 对象(一个 dict),向 dict 添加一个值并将更新后的 dict 作为 json 写回文件的演示。 It's cut and paste from an IPython session running Python 2.7.10.它是从运行 Python 2.7.10 的 IPython 会话中剪切和粘贴的。

!type test.json # prints the contents of the file test.json
{"a": [1, 3, "X", true], "b": {"hello": "world"}}

import json

with open("test.json") as json_file:
    data = json.load(json_file)
    print(data)

{u'a': [1, 3, u'X', True], u'b': {u'hello': u'world'}}

data['c'] = 'data_received' # add key: value to data

with open('test.json', 'w') as outfile:
    json.dump(data, outfile)

!type test.json # shows file contents have been updated 
{"a": [1, 3, "X", true], "c": "data_received", "b": {"hello": "world"}}

Putting all this into a function, here is a version of add_to_json:将所有这些放入一个函数中,这是 add_to_json 的一个版本:

import json
import sys

def add_to_json(json_file, node_name, value_name, value):
    update = False
    data = {}
    try:
        with open(json_file) as f:
            data = json.load(f)
    except:
        print 'opening/loading',json_file,'failed:',sys.exc_info()[0]
        return False
    if node_name in data:
        if isinstance(data[node_name],dict):
            data[node_name][value_name] = value
            update = True
        elif isinstance(data[node_name],list):
            data[node_name].append(value)
            update = True
        else:
            print value,'not added to',node_name,'since its not a list or dict'
    else: # add node_name as dict
        data[node_name] = {value_name: value}
        update = True
    if update:
        try:
            with open(json_file, 'w') as f:
                json.dump(data, f)
            print json_file,'has been updated'
            return True
        except:
            print 'writing',json_file,'failed:',sys.exc_info()[0]
            return False


!type test2.json
{"a": [1, 3, "X", true], "n": {"y": 2, "x": 1}, "e": {}, "f": []}

add_to_json('test2.json', 'n', 'z', 1)
test2.json has been updated
Out[5]: True

!type test2.json
{"a": [1, 3, "X", true], "f": [], "e": {}, "n": {"y": 2, "x": 1, "z": 1}}

add_to_json('test2.json', 'a', None, 25)
test2.json has been updated
Out[7]: True

!type test2.json
{"a": [1, 3, "X", true, 25], "n": {"y": 2, "x": 1, "z": 1}, "e": {}, "f": []}

add_to_json('test2.json', 'e', 'new_key', 'new_value')
test2.json has been updated
Out[9]: True

!type test2.json
{"a": [1, 3, "X", true, 25], "f": [], "e": {"new_key": "new_value"}, "n": {"y": 2, "x": 1, "z": 1}}

add_to_json('test2.json', 'f', None, 37)
test2.json has been updated
Out[11]: True

!type test2.json
{"a": [1, 3, "X", true, 25], "n": {"y": 2, "x": 1, "z": 1}, "e": {"new_key": "new_value"}, "f": [37]}

add_to_json('test2.json', 'new_dict', 'zebra', 23)
test2.json has been updated
Out[13]: True

!type test2.json
{"a": [1, 3, "X", true, 25], "new_dict": {"zebra": 23}, "f": [37], "e": {"new_key": "new_value"}, "n": {"y": 2, "x": 1, "z": 1}}

add_to_json('nonexistent.json', 'new_dict', 'zebra', 47)
opening/loading nonexistent.json failed: <type 'exceptions.IOError'>
Out[15]: False

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

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