我有这种格式的示例JSON:
JSON文件:
key-value
是否有任何方法可以解析JSON并循环遍历文件并打印每个json_open = open(json_file)
json_data = json.load(json_open)
print(json_data[Name]) ##should give ABC
print(json_data[Name]) ##should give ABC-1 - unsure about the syntax and format
对。
我使用的方法是使用
name=ABC
但我目前只能打印第一个对象值 - 即name=ABC-1
而非{{1}}
答案 0 :(得分:1)
您的json文件中存在错误。我修改了你的json和编写代码来遍历其中的每个元素。
错误:
Error: Parse error on line 9:
... "Country-1" }]}{ "Name": "ABC-1",
-------------------^
Expecting 'EOF', '}', ',', ']', got '{'
sample.json
{
"data": [
{
"Name": "ABC",
"Phone": "123",
"Address": [
{
"City": "City-1"
},
{
"Country": "Country-1"
}
]
},
{
"Name": "ABC-1",
"Phone": "123-1",
"Address": [
{
"City": "City-2"
},
{
"Country": "Country-2"
}
]
}
]
}
sample.py
import json
json_file='sample.json'
with open(json_file, 'r') as json_data:
data = json.load(json_data)
jin=data['data']
for emp in jin:
print ("Name :"+emp["Name"])
print ("Phone :"+emp["Phone"])
print ("City :"+emp["Address"][0]["City"])
print ("Country :"+emp["Address"][1]["Country"])
答案 1 :(得分:0)
json文件中的每条记录都以','分隔。因此,您的文件应如下所示:
[{
"Name": "ABC",
"Phone": "123",
"Address": [{
"City": "City-1"
}, {
"Country": "Country-1"
}]
},
{
"Name": "ABC-1",
"Phone": "123-1",
"Address": [{
"City": "City-2"
}, {
"Country": "Country-2"
}]
}
]
您可以按如下方式阅读文件和输出:
import json
my_file='test.json'
with open(my_file, 'r') as my_data:
data = json.load(my_data)
print data
for elm in data:
print elm['Phone']
print elm['Name']
print elm['Address'][0]['City']
print elm['Address'][1]['Country']
答案 2 :(得分:0)
首先,这不是有效的json格式,
您可以查看here您的json格式
您应该使用此try.json文件
{
"data":[{
"Name": "ABC",
"Phone":"123",
"Address":[{"City":"City-1"},{"Country":"Country-1"}]
}, {
"Name": "ABC-1",
"Phone":"123-1",
"Address":[{"City":"City-2"},{"Country":"Country-2"}]
}]
}
这是try.py
import json
json_open = open("try.json")
json_data = json.load(json_open)
for i in range(len(json_data['data'])):
print(json_data['data'][i]["Name"])
注意:python代码是用python3编写的
输出看起来就是这个
ABC
ABC-1