Python Json: using of loads, dump methods
JSON with Python
Python Json – JSON (JavaScript Object Notation) is a lightweight text-based data-interchange format, which was popularized by Douglas Crockford. It is simple for humans to read and write and easy enough for machines to parse and generate. It is based on a subset of the JavaScript Language, Standard ECMA-262 3rd Edition – December 1999. PYTHON JSON is a text format that is completely language self-dependent but uses conventions that are familiar to programmers of various languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others and all of these programming languages feature the ability
to read (parse) and generate PYTHON JSON. The built-in data types in JSON are strings, numbers, booleans (i.e., true and false), null, objects, and arrays. JSON is built on two structures:
- A collection of string: value properties. In most languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
- An ordered list of values. In various languages, this is realized as an array, vector, list, or sequence.
The two above mentioned structures are universal data structures. almost all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also is based on these structures. A PYTHON JSON object can have one or more properties, each of which is a string: value pair. An object starts with a left brace ({) and ends with a right brace (}). Each string is followed by a colon (:), and the string: value pairs are separated by a comma (,). Conventionally, a space is used after the colon. The purpose of this space is to make your code easy for people to read.
In PYTHON JSON, an array is an ordered miscellanea of values. An array starts with a left bracket ([) and ends with a right bracket (]). Values are separated by a comma (,).
In PYTHON JSON, a value can be a string in double quotes, a number, true or false or null, an object, or an array. These structures can be nested. In JSON, it is required to use double quotes around string property and single quotes are not valid.
In PYTHON JSON, a number is very much like a Python number, except that the octal and hexadecimal formats are not used. You can include the basic data types inside JSON like strings, numbers, arrays, booleans, and other object literals. This allows you to construct a data hierarchy.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
{ //Object starts "first_name": "Andrew", "middle_name": "Wood", "last_name": "Ellis", "contact": { //Object Starts "phone": "1 - 690 - 793 - 4521", }, //End Object "address": [ //Array starts { "address_type": "Office", "street": "3096 Euclid Avenue", "city": "Los Angeles", //Value String "zip_code": 90017, "state": "California" }, { "address_type": "Home", "street": "940 Lewis Street", "city": "Los Angeles", "zip_code": 90185, //Value Numbers "state": "California" } ] //Array End } //End Object |
In PYTHON JSON, an object is a list of string: value properties separated by commas, with the whole list enclosed in curly brackets. An object begins and ends with curly brackets: {}. The order of string: value properties in an object does not matter. A JSON object can have an individual string: value properties, each of which is a pairing that includes a string and a value. The string: value properties of an object must be separated by commas as in. The value of a property can be an object. The string property is case sensitive. In the above example, the string is named contact. The value of the contact property is an object that consists of an opening curly bracket, two of its own properties (string named phone and email), and a closing curly bracket. Notice how objects allow you to create a hierarchy of information, in the form of a nested string: value properties (object within the object in this case). There must be no comma after the last string: value property of an object (as in line above). Misuse of commas will break your JSON and make it impossible to parse it. Conventionally, properties of an object are set off using line breaks after the opening curly bracket, after each property, and after the closing curly bracket. Additionally, properties inside an object are indented using either tabs or spaces. The line breaks and indentation make it easy to see which properties are associated to which object.
In the above example, for the string named as address, the value is an array of objects separated by commas, with the whole array enclosed in square brackets []. The value of the address string property is an array that consists of an opening square bracket, two values (each of which is an object with five properties of its own), and a closing square bracket. Values in an array must be separated by commas (as in line above). A comma cannot be used after the last value in an array (as in line above). Conventionally, objects in an array are set off using line breaks after each opening bracket, property, or closing bracket; if a property or closing bracket is followed by a comma, the line break should be after the comma. Additionally, each object is indented within the array, and each object’s properties are further indented within that object. The line breaks and indentation make the information hierarchy clear in your JSON.Within a JSON string: value properties, certain characters, known as reserved characters, can be used only if they are preceded by a backslash (\). For example,
“text”: “The value was \”The Wizard of Oz\”.”
PYTHON JSON reserved characters are straight quotation marks (“) and backslashes (\). To include a straight quotation mark (“) or backslash (\) in the string value, escape the reserved character with a preceding backslash (\), as in the example above.
A PYTHON JSON object can be stored in its own file, which is basically just a text file with a .json extension. Alternatively, the PYTHON JSON object can exist as a string in Python. For example, the above PYTHON JSON object is stored in a file called personal_data.json. Both of these are useful when you want to transmit data across a network. It needs to be converted to a native JavaScript object when you want to access the data. The Python module called json can take Python data hierarchies and convert them to string representations; this process is called serializing. The Python json module provides methods dump() for writing data to JSON file and dumps() for writing to a Python string. Reconstructing the data from the string representation is called deserializing. The Python json module provides methods load() for turning JSON encoded data into Python objects from a file and loads() methods for turning JSON encoded data into Python objects from a string. Between serializing and deserializing, the string representing the object may have been stored in a file or sent over a network connection to some remote machine.
Example Program to Demonstrate Python Deserializing Using PYTHON JSON load() Method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import json def main(): with open('personal_data.json', 'r') as f: json_object_data = json.load(f) print(f'Type of data returned by json load is {type(json_object_data)}') print(f"First Name is {json_object_data['first_name']}") print(f"Middle Name is {json_object_data['middle_name']}") print(f"Last Name is {json_object_data['last_name']}") print(f"Phone Number is {json_object_data['contact']['phone']}") print(f"Email ID is {json_object_data['contact']['email']}") print("-----------------**************---------------") for each_json_object in json_object_data['address']: print(f"Address Type is {each_json_object['address_type']}") print(f"Street Name is {each_json_object['street']}") print(f"City Name is {each_json_object['city']}") print(f"Zip Number is {each_json_object['zip_code']}") print(f"State Name is {each_json_object['state']}") print("-----------------**************---------------") if __name__ == "__main__": main() |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Type of data returned by json load is <class 'dict'> First Name is Andrew Middle Name is Wood Last Name is Ellis Phone Number is 1 - 690 - 793 - 4521 Email ID is andrewellis@gmail.com -----------------**************--------------- Address Type is Office Street Name is 3096 Euclid Avenue City Name is Los Angeles Zip Number is 90017 State Name is California -----------------**************--------------- Address Type is Home Street Name is 940 Lewis Street City Name is Los Angeles Zip Number is 90185 State Name is California -----------------**************--------------- |
The syntax for load() method is,
json.load(fp)
Deserialize fp (a read() supporting file like object containing a PYTHON JSON document) to a Python object using the conversion. Here you import the Python Json module in line. Open the existing JSON file personal_data.json using the open() method in read mode where f is the file handler, and load that file handler using load() method. The loads() method converts a PYTHON JSON object into Python dictionary and assigns it to the json_object_data dictionary. You can display the value associated with a key ( JSON string property) by specifying the name of the dictionary json_object_data followed by brackets, within which you specify the name of the key (PYTHON JSON string property). Use a for loop to iterate through the array address values.
Example Program to Demonstrate Python Deserializing Using PYTHON JSON loads() Method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import json def main(): json_string = ''' { "title": "Product", "description": "A product from Patanjali's catalog", "category": "Ayurvedic", "item": { "name": "Aloevera Sun Screen Cream", "type": "Face Cream" } } ''' json_object_data = json.loads(json_string) print(f"Title is {json_object_data['title']}") print(f"Description is {json_object_data['description']}") print(f"Category is {json_object_data['category']}") print(f"Item name is {json_object_data['item']['name']}") print(f"Item type is {json_object_data['item']['type']}") if __name__ == "__main__": main() Output Title is Product Description is A product from Patanjali's catalog Category is Ayurvedic Item name is Aloevera Sun Screen Cream Item type is Face Cream |
The syntax for loads() method is,
json.loads(s)
Deserialize s (a str, bytes, or bytearray instance containing a PYTHON JSON document) to a Python object using the conversion. You can load a PYTHON JSON formatted string to loads() method that returns a dictionary type . Display the values by using the dictionary name with an appropriate key (JSON string property).
Example Program to Demonstrate Python Serializing Using PYTHON JSON dump() and dumps() Methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import json def main(): string_data =[{ "Name": "Debian", "Owner": "SPI" }, { "Name": "Ubuntu", "Owner": "Canonical" }, { "Name": "Fedora", "Owner": "Red Hat" 353 Introduction to Data Science }] json_data = json.dumps(string_data) print("Data in JSON format") print(json_data) with open('linux_data.json', 'w') as f: json.dump(json_data, f) if __name__ == "__main__": main() Output Data in JSON format [{"Name": "Debian", "Owner": "SPI"}, {"Name": "Ubuntu", "Owner": "Canonical"}, {"Name": "Fedora", "Owner": "Red Hat"}] |
The syntax for dumps() method is,
json.dumps(obj)
Serialize obj to a JSON formatted Python str using the conversion. The syntax for dump() method is,
json.dump(obj, fp)
Serialize obj as a PYTHON JSON formatted stream to fp (a write() supporting file like object) using the conversion. You can specify the PYTHON JSON formatted data object in your program and use the dumps() method to write a data object to a Python string . A file called linux_data.json is created and is opened in write mode. You have to specify two arguments in the dump() method, one is the data object to be serialized and the other argument is the file handler object to which data will be written. The dump() method writes data to files.
Relate Article:
https://programmingdigest.com/python-pandas-dataframe-basics/