Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python更新键的JSON值,这些键本身就是值_Python_Json_Dictionary_File Manipulation_Python Jsonschema - Fatal编程技术网

如何使用python更新键的JSON值,这些键本身就是值

如何使用python更新键的JSON值,这些键本身就是值,python,json,dictionary,file-manipulation,python-jsonschema,Python,Json,Dictionary,File Manipulation,Python Jsonschema,我有两个文件,一个是test.json,另一个是my test.py 我的目标是更新键“test3”的值,而不是等于3(如下图所示),更新并变成10 这里是test.json { "test": { "test2" : 3, "test3" : 5, "test4" : [1,2,3] }, "test5" : "hello" } 这是测

我有两个文件,一个是test.json,另一个是my test.py 我的目标是更新键“test3”的值,而不是等于3(如下图所示),更新并变成10

这里是test.json

 {
  "test": {
    "test2" : 3,
    "test3" : 5,
    "test4" : [1,2,3]
  },
  "test5" : "hello"
}
这是测试

import json
with open('test.json','r') as t:
    data = json.load(t)

data["test3"] = 10

with open ('test.json','w') as t:
    json.dump(data,t)
运行后,我期望的输出是:

 {
  "test": {
    "test2" : 3,
    "test3" : 10,
    "test4" : [1,2,3]
  },
  "test5" : "hello"
}
请注意,“test3”值变为10,但实际上,我的输出变为:

{"test": {"test2": 3, "test3": 5, "test4": [1, 2, 3]}, "test5": "hello", "test3": 10}

缩进不是问题所在,而是事实上,它没有将“test3”从5更改为10,而是添加了一个新的“test3”键,该键末尾的值为10,而旧键保持不变。我还试着让程序只打印出“test”中任何键的值,但它没有这样做,唯一有效的方法是打印出“test”本身的值或“test5”,这让我相信它们的位置是把事情弄糟的地方。如果您对此有任何疑问,我们将不胜感激,我无法将JSON文件更改为更整洁的解决方案,因为我正在使用它来处理视频游戏Minecraft中的JSON文件,我担心弄乱预先存在的结构会干扰游戏读取其文件的方式。

您访问嵌套doctory的根目录,其中没有“test3”。。从您想要的输出中,我看到您应该首先访问存储在“test”下的内部字典,然后更改它


import json
with open('test.json','r') as t:
    data = json.load(t)

data["test"]["test3"] = 10

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

data
>>>  {
  "test": {
    "test2" : 3,
    "test3" : 10,
    "test4" : [1,2,3]
  },
  "test5" : "hello"
}

您正在访问嵌套doctorial的根,其中没有“test3”。。从您想要的输出中,我看到您应该首先访问存储在“test”下的内部字典,然后更改它


import json
with open('test.json','r') as t:
    data = json.load(t)

data["test"]["test3"] = 10

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

data
>>>  {
  "test": {
    "test2" : 3,
    "test3" : 10,
    "test4" : [1,2,3]
  },
  "test5" : "hello"
}
data[“test”][“test3”]=10
data[“test”][“test3”]=10