如何使用 python 替换 json 文件中的值
How to replace a value in json file using python
我的任务是替换 json 文件中的值。
我的 json 文件在下面。在这里我需要替换以下值。
- 将“ServicePort”:“0008”替换为值 0012
- 将“PService”:“13.3.13.3”替换为值 13.12.12.12
- 将“用户名”:“root”替换为“xyz”
我的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 参数及其值的文件创建字典。
- 我已经从名为数据的文件中创建了一个字典
- 我需要通过分配下面代码中提到的字典值来更改 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)
您可以对其进行硬编码
json_data['ServicePort'] = "0012"
json_data['PService'] = "13.12.12.12"
json_data["Storage"]["username"] = "xyz"
试试这个:
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'}]}
我的任务是替换 json 文件中的值。
我的 json 文件在下面。在这里我需要替换以下值。
- 将“ServicePort”:“0008”替换为值 0012
- 将“PService”:“13.3.13.3”替换为值 13.12.12.12
- 将“用户名”:“root”替换为“xyz”
我的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 参数及其值的文件创建字典。
- 我已经从名为数据的文件中创建了一个字典
- 我需要通过分配下面代码中提到的字典值来更改 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)
您可以对其进行硬编码
json_data['ServicePort'] = "0012"
json_data['PService'] = "13.12.12.12"
json_data["Storage"]["username"] = "xyz"
试试这个:
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'}]}