Parsing JSON Using Python

in python •  7 years ago 


As a follow-up to my last video, I thought I'd do a quick demo of how to parse JSON using Python's json module.

I kinda go down the wrong path in the video, but it demonstrates a couple of useful things.

To print out a list of the coins and their info, you could try something like the untested code below:

import json

json_filename = "coins.json"
json_file = open(json_filename)
json_data = json.load(json_file)

for coin, data in json_data["coins"].items():
    print coin
    print "=" * 24
    for key, value in data.items():
        print key, "->", value

And the example below shows how you might save data into a CSV file.

import csv
import json

json_filename = "coins.json"
json_file = open(json_filename)
json_data = json.load(json_file)

csv_rows = []

for coin, data in json_data["coins"].items():
    csv_rows.append([coin] + data.values())

# Add headers
csv_rows.append(["Coin"] + data.keys())

csv_outfile = open("coins.csv", "w+")
csv_file = csv.writer(csv_outfile)

# save rows backwards (since we added headers at the end)
while csv_rows:
    csv_file.writerow(csv_rows.pop())

▶️ DTube
▶️ IPFS
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!