使用Python修改JSON文件

时间:2019-03-06 06:45:34

标签: python json

我正在尝试编写Python脚本以从JSON文件读取数据,对其进行一些计算,然后将输出写入新的JSON文件。但是我似乎无法自动化JSON读取过程。我得到这个错误。您能帮我解决这个问题吗? 非常感谢

print([a[0]][b[1]][c[1]])
TypeError: list indices must be integers or slices, not str

test.json

{
      "male": {
            "jack": {
                  "id": "001",
                  "telephone": "+31 2225 345",
                  "address": "10 Street, Aukland",
                  "balance": "1500"
            },
            "john": {
                  "id": "002",
                  "telephone": "+31 6542 365",
                  "address": "Main street, Hanota",
                  "balance": "2500"
            }
      },

      "female": {
            "kay": {
                  "id": "00",
                  "telephone": "+31 6542 365",
                  "address": "Main street, Kiro",
                  "balance": "500"
            }
      }
}

test.py

with open("q.json") as datafile:
    data = json.load(datafile)

    a = ['male', 'female']
    b = ['jack', 'john', 'kay']
    c = ['id', 'telephone', 'address', 'balance']

    print([a[1]][b[1]][c[1]])

2 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,那么您真的想从JSON打印数据,而不是中介数组。

所以:

print(data['Male'])  # will print the entire Male subsection
print(data['Male']['Jack'])  # will print the entire Jack record
print(data['Male']['Jack']['telephone'])  # will print Jack's telephone

但是也要与您的中介数组相关联:

print(data[a[0]])  # will print the entire Male subsection
print(data[a[0]][b[0]])  # will print the entire Jack record
print(data[a[0]][b[0]][c[0]])  # will print Jack's telephone

假设您正确声明了a

a = ['Male', 'Female']  # Notice the capitals

答案 1 :(得分:0)

我不知道您如何在代码中访问data,因为您直接将硬编码的值写入abc中。另外,您可以通过print(a[1], b[1], c[1])打印测试。