繁体   English   中英

如何使用 python 替换 json 文件中的值

[英]How to replace a value in json file using python

我的任务是替换 json 文件中的值。

我的 json 文件如下。 在这里我需要替换以下值。

  1. 将“ServicePort”:“0008”替换为 0012
  2. 将“PService”:“13.3.13.3”替换为值 13.12.12.12
  3. 将“用户名”:“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 参数及其值的文件中创建字典。

  1. 我从名为 data 的文件中创建了一个字典
  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)

尝试这个:

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)

Output:

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_data['ServicePort'] = "0012"
json_data['PService'] = "13.12.12.12"
json_data["Storage"]["username"] = "xyz"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM