gpt4 book ai didi

python - 在 Python for 循环中访问 JSON 数据时遇到问题

转载 作者:行者123 更新时间:2023-12-01 05:40:09 24 4
gpt4 key购买 nike

我可以读入 JSON 数据并打印数据,但由于某种原因,它以 unicode 形式读入,因此我无法使用简单的点表示法来获取数据。

测试.py:

#!/usr/bin/env python
from __future__ import print_function # This script requires python >= 2.6
import json, os

myData = json.loads(open("test.json").read())
print( json.dumps(myData, indent=2) )
print( myData["3942948"] )
print( myData["3942948"][u'myType'] )
for accnt in myData:
print( " myName: %s myType: %s " % ( accnt[u'myName'], accnt[u'myType'] ) ) # TypeError: string indices must be integers
#print( " myName: %s myType: %s " % ( accnt.myName, accnt.myType ) ) # AttributeError: 'unicode' object has no attribute 'myName'
#print( " myName: %s myType: %s " % ( accnt['myName'], accnt['myType'] ) ) # TypeError: string indices must be integers
#print( " myName: %s myType: %s " % ( accnt["myName"], accnt["myType"] ) ) # TypeError: string indices must be integers

测试.json:

{
"7190003": { "myName": "Infiniti" , "myType": "Cars" },
"3942948": { "myName": "Honda" , "myType": "Cars" }
}

运行它我得到:

> test.py
{
"3942948": {
"myType": "Cars",
"myName": "Honda"
},
"7190003": {
"myType": "Cars",
"myName": "Infiniti"
}
}
{u'myType': u'Cars', u'myName': u'Honda'}
Cars
Traceback (most recent call last):
File "test.py", line 10, in <module>
print( " myName: %s myType: %s " % ( accnt[u'myName'], accnt[u'myType'] ) )
TypeError: string indices must be integers

所以我的问题是如何读入它,以便键不是 unicode(更喜欢),或者当它们是 unicode 时如何在 for 循环中访问键。

最佳答案

您需要使用字典myData而不是字符串accnt:

for accnt in myData:
print( " myName: %s myType: %s " % ( myData[accnt][u'myName'], myData[accnt][u'myType'] ) )

您还可以在 myData 字典上使用 values() 函数:

for accnt in myData.values():
print( " myName: %s myType: %s " % ( accnt[u'myName'], accnt[u'myType'] ) )

关于python - 在 Python for 循环中访问 JSON 数据时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17756570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com