Created
August 30, 2018 15:36
-
-
Save nukopy/9737f086f40240d9a928934b9772686f to your computer and use it in GitHub Desktop.
Generate JSON file from Python-dict: Convert dict-variables to JSON file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import json | |
""" | |
explanation of json-module | |
json.load(file_obj) : file_obj --> dict | |
json.loads(json_str) : json_str --> dict | |
json.dumps(dict) : dict --> json_str | |
json.dump(dict, file_obj) : write variable-of-dict to JSON file | |
If json_file contains 2 or more objects, "json.load(file_obj)" will be to an error. | |
As JSON-file contains multiple objects, "json.load()" cannot extract 2 or more objects from JSON file at once. | |
""" | |
cities = { | |
"1": {"rank": 1, "city": "上海", "population": 24150000}, | |
"2": {"rank": 2, "city": "カラチ", "population": 23500000}, | |
"3": {"rank": 3, "city": "北京", "population": 21516000}, | |
"4": {"rank": 4, "city": "天津", "population": 14722100}, | |
"5": {"rank": 5, "city": "イスタンブル", "population": 14160467} | |
} | |
# By mode="w", you can write variables of dict to new file as JSON file. | |
with open("output/top_cities.json", mode="w", encoding="utf-8") as f: | |
json.dump(cities, f) # dict to JSON file | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment