[英]How do I choose what to parse from json?
我已经设法将json文件加载到python中,但是只能从标头中获取信息,如何从标头中的列表中获取信息? 抱歉,如果这是非常基本的操作,但我对Google没有好运,因为我不知道要搜索什么。 谢谢。
这就是我导入文件并尝试打印名称和链接的方式:
import json
with open('scrape.json') as json_file:
data = json.load(json_file)
for p in data[0]:
print('Name: ' + p[0])
print('Website: ' + p[1])
这就是我的json文件的格式:
[
{"product_name": ["title1"], "product_link": ["www.url1.com"]},
{"product_name": ["title2"], "product_link": ["www.url2.com"]},
{"product_name": ["title3"], "product_link": ["www.url3.com"]},
]
我得到的输出是
Name: p
Website: r
此信息来自“ product_name”的第一行和前两个字符
我想要的输出是“ title1”和“ www.url1.com”,然后我也想从每一行获取输出。
您必须使用键来获取值,并且由于您的值是列表,因此可以获取索引0即[0]来获取值:
with open('scrape.json') as json_file:
data = json.load(json_file)
for p in data[0]:
print('Name: ' + p["product_name"][0])
print('Website: ' + p["product_link"][0])
这样写
with open('scrape.json') as json_file:
data = json.load(json_file)
for p in data[0]:
print('Name: ' + p["product_name"])
print('Website: ' + p["product_link"])
遍历字典会产生其键,因此:
for p in data[0]:
print(p)
将打印"product_name"
和"product_link"
。
而是通过键访问值:
for product in data:
print('Name:', product['product_name'][0])
print('Link:', product['product_link'][0])
尝试这个:
import json
with open('scrape.json') as json_file:
data = json.load(json_file)
for d in data:
print('Name: ' + d["product_name"][0])
print('Website: ' + d["product_link"][0])
因此,它的工作方式是:遍历列表中的所有字典,并打印键product_name
和product_link
值(由于它们是列表,因此需要打印这些值的第一个元素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.