I have managed to load the json file into python but can only get information from the headers, how can I get the information from the lists within them? Sorry if this is very basic but I've had no luck on google as I don't know what to search. Thanks.
This is how I am importing the file and trying to print the name and link:
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])
And this is how my json file is formatted:
[
{"product_name": ["title1"], "product_link": ["www.url1.com"]},
{"product_name": ["title2"], "product_link": ["www.url2.com"]},
{"product_name": ["title3"], "product_link": ["www.url3.com"]},
]
The output I get is
Name: p
Website: r
This info is from the first line and first 2 characters of "product_name"
The output I want is "title1" and "www.url1.com", I also then want to get the output from each line.
You must use the keys to get the values and since your values are lists, you can get the index 0 ie [0] to get the values:
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])
Write it like this
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"])
Iterating through a dictionary yields its keys, so:
for p in data[0]:
print(p)
will print "product_name"
and "product_link"
.
Access the values by keys instead:
for product in data:
print('Name:', product['product_name'][0])
print('Link:', product['product_link'][0])
try this:
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])
So how this works is: You go through all the dictionaries inside your list and print values for keys product_name
and product_link
(you need to print first element of those valuues since they are lists).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.