我的任务是替换json文件中的一个值。
我的json文件在下面。在这里,我需要替换以下值。
将“13.12.12.12
。
我的json文件
{
"version": "35.1",
"ServicePort": "0008",
"APIService": "14.414.4",
"Storage": [
{
"PService": "13.3.13.3",
"username": "root",
"Number": 121,
"IP": "10.2.10.2"
}
]
}我执行上述任务的Python代码是
import os
import sys
import json
with open('/xyz/Test/Conf.json', 'r') as fh:
json_data = json.load(fh)
for item in json_data:
if item['Number'] in ["121"]:
item['Number'] = "132"
with open('/xyz/Test/Conf.json', 'w') as fh:
json.dump(json_data, fh, indent=2)在这里,我不能做同样的和与下面的错误击中,请一些人帮助我的代码出了什么问题。
错误:
if item['Number'] in ["121"]:
TypeError: string indices must be integers要求2:
我得稍微修改一下代码。所需的是从包含json参数及其值的文件创建字典。
下面的代码所述。
代码中的更改--赋值来自字典--这是没有发生的。
D = {}
with open("data") as f:
for line in f:
(key, val) = line.split()
D[key] = val
print(D)
for item in json_data:
print(item, ": ", type(item))
print("-----------get keys and values from dict----------------")
for key, value in json_data.items():
print(key, ": ", type(key), value, ": ", type(value))
print("----------try to change-----------------")
for key, value in json_data.items():
if key == "Storage":
for i in range(len(value)):
if json_data["Storage"][i]["Number"] == 121:
json_data["Storage"][i]["Number"] = D['Number'] # <--- this is the change i need, may you please suggest any solution here, this assignment is not working
print(json_data)发布于 2021-05-08 18:21:58
试试这个:
for item in json_data:
print(item, ": ", type(item))
print("-----------get keys and values from dict----------------")
for key, value in json_data.items():
print(key, ": ", type(key), value, ": ", type(value))
print("----------try to change-----------------")
for key, value in json_data.items():
if key == "Storage":
for i in range(len(value)):
if json_data["Storage"][i]["Number"] == 121:
json_data["Storage"][i]["Number"] = 132
print(json_data)输出:
version : <class 'str'>
ServicePort : <class 'str'>
APIService : <class 'str'>
Storage : <class 'str'>
-----------get keys and values from dict----------------
version : <class 'str'> 35.1 : <class 'str'>
ServicePort : <class 'str'> 0008 : <class 'str'>
APIService : <class 'str'> 14.414.4 : <class 'str'>
Storage : <class 'str'> [{'PService': '13.3.13.3', 'username': 'root', 'Number': 121, 'IP': '10.2.10.2'}] : <class 'list'>
----------try to change-----------------
{'version': '35.1', 'ServicePort': '0008', 'APIService': '14.414.4', 'Storage': [{'PService': '13.3.13.3', 'username': 'root', 'Number': 132, 'IP': '10.2.10.2'}]}发布于 2021-05-08 18:13:28
你可以硬编码
json_data['ServicePort'] = "0012"
json_data['PService'] = "13.12.12.12"
json_data["Storage"]["username"] = "xyz"https://stackoverflow.com/questions/67450616
复制相似问题