0

I have a list of returned values from a json file

2020-09-08 - 11290
2020-09-09 - 11290
2020-09-10 - 11290
2020-09-11 - 12290

I saved above values to a variable "data". These values are returned from a json list by using print(data)

print(f"{node['X']} - {node['Y']}") #print(data)

I want this list of returned values into a csv file with a header "X" and "Y"

fieldnames = ['X', 'Y']
with open('mydata.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(chain.from_iterable(data))

This piece of code is returning empty data with just two headers given "X" and "Y" It would be great if i get a suggestion or a solution with some example. Thanks for the help!

2
  • did you think about how the format will fit? What about a list, sublist on the JSON Commented Nov 20, 2020 at 13:26
  • Does this answer your question? How can I convert JSON to CSV? Commented Nov 20, 2020 at 13:27

1 Answer 1

1

I think it might be worth mentioning your previous question or at least providing more details related to the data you're trying to write.

Anyhow, this should get you what you want:

import csv
import requests

response = requests.get('https://www.prisjakt.nu/_internal/graphql?release=2020-11-20T07:33:45Z|db08e4bc&version=6f2bf5&main=product&variables={"id":5183925,"offset":0,"section":"statistics","statisticsTime":"1970-01-02","marketCode":"se","personalizationExcludeCategories":[],"userActions":true,"badges":true,"media":true,"campaign":true,"relatedProducts":true,"campaignDeals":true,"priceHistory":true,"recommendations":true,"campaignId":2,"personalizationClientId":"","pulseEnvironmentId":"sdrn:schibsted:environment:undefined"}').json()

with open("your_data.csv", "w") as output:
    w = csv.DictWriter(output, fieldnames={"date", "lowestPrice"})
    w.writeheader()
    for node in response["data"]["product"]["statistics"]["nodes"]:
        w.writerow(node)

Output from the .csv file:

lowestPrice,date
13195,2019-09-10
12990,2019-09-11
12990,2019-09-12
12605,2019-09-13
12605,2019-09-14
12605,2019-09-15
12970,2019-09-16
12970,2019-09-17
12970,2019-09-18
...
Sign up to request clarification or add additional context in comments.

4 Comments

Neat and clean. You are really fast. I would learn these skills from you. Thanks for the help!
If you want the date first, just swap the order of fieldnames.
Yes, i got that
Cool! Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.