Parsing JSON Using Python

in #python7 years ago

<hr /><p> <p dir="auto">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. <p dir="auto">I kinda go down the wrong path in the video, but it demonstrates a couple of useful things. <p dir="auto">To print out a list of the coins and their info, you could try something like the untested code below: <pre><code>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 <p dir="auto">And the example below shows how you might save data into a CSV file. <pre><code>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()) <hr /><a href="https://d.tube/#!/v/whs/rhjkh468" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link"> ▶️ DTube<br /><a href="https://ipfs.io/ipfs/Qmb83XepXKVCaMtZwuJRyt8vqtPpPtEmFuNJXhjRMfc6Yh" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link"> ▶️ IPFS