- Example - Read JSON from file as dictionary
- Example - Read JSON Array from file as list
- Example - Read JSON from input string as dictionary
- Example - Convert Python dictionary to JSON
- Example - Write JSON to file
- Example - Convert YAML to JSON
- Example - Convert JSON to YAML
- Example - Convert XML to JSON
- Example - Convert JSON to XML
Yaml and XML examples below need the Python Yaml and xmltodict modules to be installed.
pip3 install yaml pip3 install xmltodict
Sample Input files
{ "id": "1", "title": "Black Panther", "year": "2018", "genres": [ "Action", "Adventure", "Sci-Fi" ], "contentRating": "15", "duration": "PT134M", "releaseDate": "2018-02-14", "averageRating": 0, "originalTitle": "", "actors": [ "Chadwick Boseman", "Michael B. Jordan", "Lupita Nyong'o" ], "imdbRating": 7.0 }
[ { "id": "1", "title": "Black Panther", "year": "2018", "genres": [ "Action", "Adventure", "Sci-Fi" ], "contentRating": "15", "duration": "PT134M", "releaseDate": "2018-02-14", "averageRating": 0, "originalTitle": "", "actors": [ "Chadwick Boseman", "Michael B. Jordan", "Lupita Nyong'o" ], "imdbRating": 7.0 }, { "id": "2", "title": "Grottmannen Dug", "year": "2018", "genres": [ "Animation", "Adventure", "Comedy" ], "contentRating": "PG", "duration": "PT89M", "releaseDate": "2018-03-23", "averageRating": 0, "originalTitle": "Early Man", "actors": [ "Tom Hiddleston", "Eddie Redmayne", "Maisie Williams" ], "imdbRating": 6.3 } ]
--- - actors: - Chadwick Boseman - Michael B. Jordan - Lupita Nyong'o averageRating: 0 contentRating: '15' duration: PT134M genres: - Action - Adventure - Sci-Fi id: '1' imdbRating: 7.0 originalTitle: '' releaseDate: '2018-02-14' title: Black Panther year: '2018' - actors: - Tom Hiddleston - Eddie Redmayne - Maisie Williams averageRating: 0 contentRating: PG duration: PT89M genres: - Animation - Adventure - Comedy id: '2' imdbRating: 6.3 originalTitle: Early Man releaseDate: '2018-03-23' title: Grottmannen Dug year: '2018'
<?xml version="1.0" encoding="UTF-8"?> <movies> <movie> <id>1</id> <title>Black Panther</title> <year>2018</year> <genres>Action</genres> <genres>Adventure</genres> <genres>Sci-Fi</genres> <contentRating>15</contentRating> <duration>PT134M</duration> <releaseDate>2018-02-14</releaseDate> <averageRating>0</averageRating> <originalTitle /> <actors>Chadwick Boseman</actors> <actors>Michael B. Jordan</actors> <actors>Lupita Nyong'o</actors> <imdbRating>7.0</imdbRating> </movie> </movies>
Example - Read JSON from file as dictionary
import json # Read JSON from file as dictionary def read_json_from_file(): # Read JSON from file try: f = open("sample.json", "r") movie = json.load(f) print(movie) print(type(movie)) # movie is of type dict # Get title from dict print("Title is : " + movie["title"]) # Get list of genres print(type(movie["genres"])) # data["genres"] is list for genre in movie["genres"]: print(genre) except Exception as e: print("Error: " + str(e)) finally: f.close() def main(): read_json_from_file() main()
Example - Read JSON Array from file as dictionary
import json # Read JSON Array from file as List def read_json_array_from_file(): # Read JSON from file try: f = open("sample_array.json", "r") movie_list = json.load(f) print(movie_list) print(type(movie_list)) # movie_list is of type list # Iterate over the list for movie in movie_list: print(movie["title"]) except Exception as e: print("Error: " + str(e)) finally: f.close() def main(): read_json_array_from_file() main()
Example - Read JSON from input string as dictionary
import json # Read JSON from input string as dictionary def read_json_from_str(): json_input = """ { "id": "2", "title": "Grottmannen Dug", "year": "2018", "genres": [ "Animation", "Adventure", "Comedy" ], "contentRating": "PG", "duration": "PT89M", "releaseDate": "2018-03-23", "averageRating": 0, "originalTitle": "Early Man", "actors": [ "Tom Hiddleston", "Eddie Redmayne", "Maisie Williams" ], "imdbRating": 6.3 } """ try: movie = json.loads(json_input) print(movie) print(type(movie)) # movie is of type dict # Get title from dict print("Title is : " + movie["title"]) # Get list of genres print(type(movie["genres"])) # data["genres"] is list for genre in movie["genres"]: print(genre) except Exception as e: print("Error: " + str(e)) def main(): read_json_from_str() main()
Example - Convert Python dictionary to JSON
import json # Write Python objects to JSON # Convert Python dict to JSON def write_objects_to_json(): movie = { "id": 4, "title": "Grottmannen Dug", "actors": ["Tom Hiddleston","Eddie Redmayne","Maisie Williams"], "imdbRating": 6.3, "before2022": True } print(type(movie)) print(json.dumps(movie)) # Pretty print JSON print(json.dumps(movie, indent=4)) # Pretty print JSON and sort keys print(json.dumps(movie, indent=4, sort_keys=True)) def main(): write_objects_to_json() main()
Example - Write JSON to file
import json # Write JSON to file def write_objects_to_json_file(): movie = { "id": 4, "title": "Grottmannen Dug", "actors": ["Tom Hiddleston","Eddie Redmayne","Maisie Williams"], "imdbRating": 6.3, "before2022": True } print(type(movie)) try: f = open("output.json", "w") f.write(json.dumps(movie, indent=4, sort_keys=True)) except Exception as e: print("Error: " + str(e)) finally: f.close() def main(): write_objects_to_json_file() main()
Example - Convert YAML to JSON
import json import yaml from yaml import Loader # Convert YAML to JSON def convert_yaml_to_json(): # Read YAML from file try: f = open("sample.yaml", "r") data = yaml.load(f, Loader=Loader) print(json.dumps(data, indent=4)) except Exception as e: print("Error: " + str(e)) finally: f.close() def main(): convert_yaml_to_json() main()
Example - Convert JSON to YAML
import json import yaml from yaml import Loader # Convert JSON to YAML def convert_json_to_yaml(): # Read JSON from file try: f = open("sample_array.json", "r") movie_list = json.load(f) f = open("output.yaml", "w") yaml.dump(movie_list, f, explicit_start=True) except Exception as e: print("Error: " + str(e)) finally: f.close() return None def main(): convert_json_to_yaml() main()
Example - Convert XML to JSON
import json import xmltodict # Convert XML to JSON def convert_xml_to_json(): # Read XML from file try: f = open("sample.xml", "r") movie = xmltodict.parse(f.read()) print(type(movie)) print(json.dumps(movie, indent=4)) except Exception as e: print("Error: " + str(e)) finally: f.close() return None def main(): convert_xml_to_json() main()
Example - Convert JSON to XML
import json import xmltodict def convert_json_to_xml(): json_input = """ { "movies": [ { "id": "1", "title": "Black Panther", "year": "2018", "genres": [ "Action", "Adventure", "Sci-Fi" ], "contentRating": "15", "duration": "PT134M", "actors": [ "Chadwick Boseman", "Michael B. Jordan" ], "imdbRating": 7.0 } ] } """ # Read JSON from input string try: movie = json.loads(json_input) print(type(movie)) print(xmltodict.unparse(movie, full_document=False, pretty=True)) except Exception as e: print("Error: " + str(e)) return None def main(): convert_json_to_xml() main()
0 comments:
Post a Comment