我正在尝试读取JSON文件并对其进行遍历,例如,我正在尝试打印孩子,名字,爱好等...
JSON文件如下所示:
{
"firstName": "Jane",
"lastName": "Doe",
"hobbies": ["running", "sky diving", "singing"],
"age": 35,
"children": [
{
"firstName": "Alice",
"age": 6
},
{
"firstName": "Bob",
"age": 8
}
]
},
{
"firstName": "Mike",
"lastName": "Smith",
"hobbies": ["bowling", "photography", "biking"],
"age":40,
"children": [
{
"firstName": "Steve",
"age": 10
},
{
"firstName": "Sara",
"age": 18
}
]
}
我正在使用以下代码加载json文件:
import json
with open('test.json') as f:
data = json.load(f)
这样我就可以很好地打印第一条记录的一部分了:
print(data['children'])
print(data['hobbies'])
[{'firstName': 'Alice', 'age': 6}, {'firstName': 'Bob', 'age': 8}]
['running', 'sky diving', 'singing']
尽管如此,我还是想遍历记录,以便我也可以打印第二条(或第三条,或20条,如果适用)
但是,当我尝试此操作时:
for key, value in data.items():
print(key, value)
它仍然只返回第一个条目:
firstName Jane
lastName Doe
hobbies ['running', 'sky diving', 'singing']
age 35
children [{'firstName': 'Alice', 'age': 6}, {'firstName': 'Bob', 'age': 8}]
有什么想法吗?
答案 0 :(得分:1)
您面临的问题是您将数据作为单个json。
您需要将其制成数组。像这样的东西。
batchProcessPromises([...queue], 10)
.then(() => {
console.log('Time to get one with my day', queue)
})
然后,您需要将其循环遍历列表,然后根据所写内容进行循环。像这样
source("https://bioconductor.org/biocLite.R")
biocLite("rtracklayer")
library(rtracklayer)
import("example.bed", format="bed")
答案 1 :(得分:1)
要隐藏您的文件,请添加更多std JSON
,然后打开并添加[
和]
,使其成为json列表。并将整个代码粘贴到下面:
import json
f = open("test_json.txt", "r")
contents = f.readlines()
f.close()
contents.insert(0, "[")
f = open("test_json.txt", "w")
contents = "".join(contents)
f.write(contents)
f.write("]")
f.close()
with open("test_json.txt", "r") as fd:
d = json.load(fd)
for i in d:
print(i)