How to Read Json Data in Python

How to read JSON file in Python

In this commodity, we will learn diverse means to read JSON files in Python. Nosotros will use some built-in functions available in Python for JSON and some related custom examples every bit well. Nosotros will compare text each part with examples in this module. Let'due south first have a quick look over the full form of JSON, an introduction to JSON, and how JSON files are used. Look at the following examples showing different parsing functions to read JSON documents in Python.

What is JSON?

JSON stands for JavaScript Object Notation. It is a popular data format used for representing structured information. Information technology is a lightweight format that is used for data interchanging. The data representation in JSON is similar to that of Python Dictionary. It is a collection of name/value pairs. In JSON, it is mutual to transmit and receive data between a server and spider web application in JSON format. It is likewise common to shop a JSON object in a file. JSON data can be in the form of the object, assortment, value, string, or number.

In Python, JSON exists as a string or more like a dictionary having central-value pairs where keys must be a string and values tin can be of any type say object, array, value, string, or a number.

JSON Example

          data = '{"model number": "RX234", "customers": ["Adam", "Paul"], "toll": 45000, "quantity": 12, "company": "Samsung"}'        

For reading any JSON file and to work with JSON (string, or file containing JSON object) you must import JSON module in python script.

Reading JSON file in Python

Reading JSON files in Python linguistic communication is quite easy. We just need to import JSON module in the file and utilize its methods. Reading of JSON information is carried out using either of the following functions.

  1. json.load()

  2. json.loads()

  3. json.dumps()

1. Reading JSON Using json.load() Role

Python provides json.load() method to read a file containing the JSON object. Reading JSON data from a file is quite an like shooting fish in a barrel job in python equally python script provides a built-in JSON module and JSON has a congenital-in load() part to carry out the parsing process. Using the aforementioned JSON module, we can excerpt and parse the JSON cord straight from a file object. This method is used when the programmer already has a JSON file with structured data.

Syntax

          json.load(file object)        

Sample JSON File

This JSON file, we will read with the python script.

          {"model number": "RX234",  "customers": ["Adam", "Paul"],  "price": 45000,  "quantity": 12,  "company": "Samsung" }        

Example

In the following example, we are going to read a JSON file and then impress out the data. This json.load() function reads the string from the JSON file. The json.load(file) part creates and returns a new Python dictionary with the fundamental-value pairs in the JSON file. Then, this lexicon is assigned to the data variable, and the issue is displayed.

          import json  with open up('path_to_file/model.json') as f:      data = json.load(f)  impress(data)        


{"model number": "RX234", "customers": ["Adam", "Paul"], "price": 45000, "quantity": 12, "visitor": "Samsung"}

In the in a higher place code to read the JSON file, kickoff, we have imported the JSON module and then we have used the open() function to read the JSON file bypassing the JSON file path along with the proper noun of the file equally an argument. So, the file is parsed using json.load() method which gives us a dictionary and the effect is stored in the information variable. As shown in the output, the JSON string is printed in the grade of key-value pairs.

2. Reading JSON Using json.loads() Function

If you have a JSON string rather than a JSON file then you can parse information technology past using the json.loads() method. The json.loads() method does not take the file path, simply the file contents every bit a string, using the fileobject.read(). With json.loads() part, we can return the content of the file. This part is useful to the programmer when he has a JSON cord.

Syntax

          json.loads(jsonstring) #for Json string  json.loads(fileobject.read()) #for fileobject        

Instance

The given case will show how to read a JSON string, as well as a file object past using JSON module in Python.

          import json     # JSON cord  a =  '{"name": "Flora", "age": 16, "identify": "london"}'  # deserializes into dict and returns dict.  y = json.loads(a)     impress("JSON string = ", y)  print()           # JSON file  f = open ('model.json', "r")     # Reading from file  information = json.loads(f.read())     print(information)        


JSON cord = {"proper noun": "Flora", "age": 16, "place": "london"}'
{"model number": "RX234", "customers": ["Adam", "Paul"], "cost": 45000, "quantity": 12, "company": "Samsung"}

3. Reading JSON Using json.dumps() Function

This is quite the aforementioned every bit json.load() but with additional parameters and functionality. The json.dumps() makes the original JSON output a human-readable output course with proper indentation. This process of presenting JSON data into a human being-readable format with proper indentation and spacing is known equally Pretty Printing. Pretty Press is washed past easily passing an integer value to the indent parameter.

Syntax

          json.dumps(JSON string, indent parameter)        

Instance

Here, we used the dumps() function to read JSON cord in human being-readable form.

          import json  #ascertain JSON string information = {'model':[{'number': 'RX341', 'toll': 35000, 'qty': 12, 'visitor': 'Samsung'}]}  #use dumps() with ii parameters and shop resultant in consequence variable result= json.dumps(data, indent=four)  print(consequence)        


{
"model": [
{
"number": "RX341",
"toll": "35000",
"qty": "12",
"visitor": "Samsung"
}
]
}

As you can see in the in a higher place output, the indent parameter is set to 4. This is actually quite useful since you lot'll often have to read JSON data during development.

In the given figure, you can see json.loads() converts a string to JSON object while json.dumps() converts JSON object to string.

Conclusion

In this commodity, we learned about JSON files and how nosotros use JSON strings and file objects. We learned dissimilar means to read JSON file past three built-in JSON functions - json.load(), json.loads() and json.dumps(). We also used the fileobject.read() part to read file object. We saw differences between the functions. Nosotros used some custom parsing codes as well to parse the JSON file using dissimilar JSON files.

ingramtheyearect1981.blogspot.com

Source: https://www.studytonight.com/python-howtos/how-to-read-json-file-in-python

0 Response to "How to Read Json Data in Python"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel