如何使用python在JSON文件中添加内容?

时间:2014-05-19 14:07:32

标签: python json

耶。 (对不起,我的英文不好T_T)

{
  "BlockA": {
    "BlockB": {
      "name": "BlockB",
      "value": "Value_B"
    }
}

这只是我简单的json文件。

并且,我需要更改

{
  "BlockA": {
    "BlockB": {
      "name": "BlockB",
      "value": "Value_B"
    },
    "BlockC": {
      "name": "BlockC",
      "value": "Value_C"
    }
}

像这样,我试过追加,json.loads,json.load,json.dumps,json.dump .. 但所有功能都给了我错误。

我试过了,

import json
f = open(".\simple.json", "r")
json_obj = json.load(f)

#json_obj.append << doesnt work
#json_obj.dump("blahblah", Ensureblahblah=False) << doesnt work too.

使用python版本3.4.1

2 个答案:

答案 0 :(得分:4)

JSON只是一种序列化数据的方法。如果你解析一个JSON对象,你将得到一个python字典。如果你解析一个JSON数组,你将得到一个python列表。如果你解析一个字符串,你会得到一个字符串......等等。

因此,如果你解析一个JS对象,你就会得到一本字典。词典没有附加或转储方法。

这意味着:

import json
f = open(".\simple.json", "r")
json_obj = json.load(f)  # <--- this is a dictionary!

json_obj['BlockC'] = {'name': '...', 'value': '...'}

然后将其转储回文件(如果您有疑问,请阅读json API)

答案 1 :(得分:1)

以下是代码指导说明

import json

open_file_object = open("/home/action/workspace/playkt/data.json", 'r')
decoded_json = json.load(open_file_object)

print (decoded_json)

"""
{
  "BlockA": {
    "BlockB": {
      "name": "BlockB",
      "value": "Value_B"
    }
  }
}
"""

decoded_json["BlockA"]["BlockC"] = { "name": "BlockC", "value": "Value_C" }

print(decoded_json)

"""
{
    "BlockA": {
        "BlockB": {
            "name": "BlockB",
            "value": "Value_B"
        },
        "BlockC": {
            "name": "BlockC",
            "value": "Value_C"
        }
    }
}
"""

#write to file 
output_file = "/home/action/workspace/playkt/data.json"

with open(output_file, 'w') as write_file_object:
  #Serialize dictionary to a JSON formatted string and write to file
  write_file_object.write(json.dumps(decoded_json))