社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

用python修改json文件

brabbit640 • 5 年前 • 217 次点击  

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

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

杰森

{
      "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"
            }
      }
}

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]])
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40264
 
217 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Tobias S
Reply   •   1 楼
Tobias S    6 年前

我不知道,你是怎么进入的 data 在您的代码中,因为您直接将硬编码值写入 a , b c . 此外,您还可以通过以下方式打印您的测试: print(a[1], b[1], c[1]) .

velis
Reply   •   2 楼
velis    6 年前

如果我理解正确的话,您真的希望从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