为现有JSON文件添加值

时间:2015-09-08 15:57:34

标签: python json

我想定义以下简单函数:

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

其中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)

我已经搜索了如何使用json.load()函数,但如果我给它一个字符串,我会收到此错误:

enter image description here

我不确定要给json.load什么;如何将文件的路径作为输入?

1 个答案:

答案 0 :(得分:0)

这是一个将现有json文件中的数据读入Python对象(dict)的演示,向dict添加一个值并将更新后的dict作为json写回文件。它是从运行Python 2.7.10的IPython会话中剪切和粘贴的。

library(data.table)
CPU_ALL=data.table(`User%`=1:2)
CPU_ALL$`User%`
# [1] 1 2
CPU_ALL[,`User%`]
# [1] 1 2
CPU_ALL[,.(`User%`)]
#    User%
# 1:     1
# 2:     2
CPU_ALL[`User%` %in% 1:2]
#    User%
# 1:     1
# 2:     2
CPU_ALL[["User%"]]
# [1] 1 2

将所有这些放入一个函数中,这是add_to_json的一个版本:

!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"}}