Python Can';t从json编码密钥的内容
我想在我的Python Can';t从json编码密钥的内容,python,json,Python,Json,我想在我的json文件中打印属于我的id键的每个值。我正在使用以下代码打印整个文件: import json from pprint import pprint with open('f:\Docs\testList.json') as data_file: data = json.load(data_file) pprint( data ) 下面是json { "clubs": [ { "location": "Dallas",
json
文件中打印属于我的id
键的每个值。我正在使用以下代码打印整个文件:
import json
from pprint import pprint
with open('f:\Docs\testList.json') as data_file:
data = json.load(data_file)
pprint( data )
下面是json
{ "clubs": [
{
"location": "Dallas",
"id": "013325K52",
"type": "bar"
},
{
"location": "Dallas",
"id": "763825X56",
"type": "restaurant"
}
] }
它工作正常,但是我无法确定data\u文件
和data
变量的类型,因此我不知道如何编写for循环来打印内容。我对Python真的很陌生,但在伪代码中我会这样做(如果我假设数据
是字典
对象的数组(或Python列表):
或
如果有人能给我指明正确的方向或给予指导,我将不胜感激,因为我真的没有主意。我查看了json模块的文档,但没有弄清楚它到底做了什么以及如何做。这应该相当简单,这里有一个非常明确的方法(我把它做得更长,这样对您来说更清晰,您可以更有效地做这件事)
data\u file
是一个文件,即:用于读取文本的文件对象。你不应该在意它
数据
是一个。字典映射键值对,但您可能已经知道这一点<代码>数据
有一个键,“clubs”
,它映射到。此列表包含其他词典
您的伪代码:
for dictionaryVar in jsonArray
print dictionaryVar["id"]
for dictionaryVar in jsonArray
if dictionaryVar containsKey: "id"
print dictionaryVar["id"]
对应于以下Python代码:
for item in data['clubs']:
print item['id']
for item in data['clubs']:
if 'id' in item:
print item['id']
您的伪代码:
for dictionaryVar in jsonArray
print dictionaryVar["id"]
for dictionaryVar in jsonArray
if dictionaryVar containsKey: "id"
print dictionaryVar["id"]
对应于以下Python代码:
for item in data['clubs']:
print item['id']
for item in data['clubs']:
if 'id' in item:
print item['id']
如果
club\u id
是0
,该怎么办?谢谢@andreacorbellini,我修改为专门检查无。这是一个非常有用的答案,我非常喜欢你也解释了数据类型!谢谢你,安德里亚!