Python json array parsing

How to get values from json array in Python

In this Python tutorial, I will show you, how to get values from JSON array in Python. Also, I will explain, how to extract specific data from JSON in Python. Finally, I will show you how to read a JSON file in Python.

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It’s widely used to store and exchange data in web applications.

Introduction to JSON in Python

Python has a built-in module called json which can be used to work with JSON data. JSON data structures consist of arrays and objects. In Python, JSON arrays are equivalent to lists and JSON objects are equivalent to dictionaries.

Here’s an example of JSON data representing cities like below:

Read JSON File in Python

Let us see, how to read a JSON file in Python.

To read JSON data from a file, you can use the built-in open() function to open the file and then use the json.load() function to parse the JSON data in Python.

First, let’s create a file named cities.json with the above JSON data.

Now, let’s write a Python code to read this data:

import json # Open the JSON file for reading with open('cities.json', 'r') as file: # Parse JSON data data = json.load(file) # Display the data print(data) 

How to Parse JSON Data in Python

Let us now check out how to parse JSON data in Python.

The json module also allows you to parse JSON data from a string using the json.loads() function.

import json json_string = '' # Parse JSON data from a string city = json.loads(json_string) # Display the data print(city) 

You can see the output below:

how to get values from json array in python

Python extract value from JSON array

Let us now see, how to extract value from JSON array in Python.

Let’s extract values from the JSON array. The JSON array here contains objects, and each object represents a city.

# Using the data loaded earlier from the file cities = data['cities'] # Loop through the array and print each city name for city in cities: print(city['name']) 
New York Los Angeles Chicago 

Extract specific data from JSON in Python

Now. let us see, how to extract specific data from JSON in Python.

Sometimes you might only need specific data from the JSON. Let’s say you only want the names of the cities that have a population of over 3 million.

# Loop through the array and print names of cities with population > 3 million for city in cities: if city['population'] > 3000000: print(city['name']) 

Conclusion

In this tutorial, we have learned how to read JSON data from a file and parse JSON data in Python. We have also learned how to extract values and specific data from JSON arrays. The json module in Python makes it easy to work with JSON data, allowing for the encoding and decoding of JSON to Python data structures like lists and dictionaries.

Читайте также:  Java на китайский айфон

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

How to Extract Data from JSON File in Python?

How to Extract Data from JSON File in Python?

In this tutorial, you will learn how to parse JSON file and extract data from file in python? We will look at how we can use ‘json’ module to read the json object and get the value from json array?

The JSON stands for JavaScript Object Notation and it is a very popular lightweight data-interchanging format. We use the JSON to serialize the data have a key pair value data. The JSON object same looks like dictionaries in python.

So, here we will see how you can read the JSON data in python and extract the specific data from the file? We will use the ‘json’ python module. You don’t need to install it using the pip because it’s an in-built module. You can just use it by importing it into the file.

Let’s get started to play with json data in python.

Parse JSON Object in Python

In this example, we will parse the simple json object string that we will create in python. So first thing you need to import the ‘json‘ module into the file.

Then create a simple json object string in python and assign it to a variable.

Now we will use the loads() function from ‘json‘ module to load the json data from the variable. We store the json data as a string in python with quotes notation.

And then we will use the dumps() function from the ‘json‘ module to convert the python string to a JSON object. Now it’s ready to print your json object in python. See the following example code.

In the above code, we print the json data and used the indent for indentation. You can also use the sort in print to sorting the result. So when you run the above code you will get the output like below.

Output:

Now if you want to iterate this json data then just simply use the loop to prin each data one by one. I’m going to use for loop to print it.

Читайте также:  Python save file to disk
Output:
python: 1 php: 2 c: 3 vb: 4 perl: 5

Hope you understand the basic of parsing the JSON object in python and print the value from it. Let’s now work with file to extract data it using the ‘json’ python module.

Lexa Django Template

Parse JSON File in Python

In this example, we will learn how to extract data from json file in python. In the above example, we saw the parse simple JSON object and in this example, we will do the same but first, we will create a json file with .json extension.

Let’s create the json_data.json file with the following JSON object OR you can download it from here. And you can also use my JSON formatter tool to minify and beautify json object and download it.

To Load this json file in python, we will first open this file as a read mode using the open() function.

The above code will print your json data from the file. It will store the JSON as python dictionaries, you can check the type of json_load variable using the type(json_load) .

Now you can use it in python and get the data from it which you want to use in the program. You can get the specific index data or you can loop through all data.

Let’s look at how to extract specific data from json file object in python that we have printed above example.

Extract Specific Data from JSON File

As we have store json in the json_data variable, now we will use this variable to get the specific value from the json array.

I will use the key represent to index to get that value from JSON object.

For example, if I want to print all ‘languages‘ from the ‘web‘ JSON object then I will use the following code.

Output:

If you want to get only first language the use the following

Output:

Just use the index of the array to get any languages and I’m sure you know that array index always starts from ‘0’.

JSON Array Loop Through Data

As you see in the above example, we fetched all languages and print them as objects. Now if you want to loop the value and print each language one by one then we will use the for loop to do it.

Output:
1 PHP https://www.php.net/ 2 Python https://www.python.org/ 3 Java https://www.java.com/en/

Hope you understand the tutorial how to extract the data from JSON file in python and how to fetch specific data from JSON array.

If you have questions please let me know in the comment section I would love to help you with that.

Источник

Parse JSON Array of Objects in Python

Parse JSON Array of Objects in Python

  1. JavaScript Object Notation
  2. JSON Objects in Python
  3. Parse JSON Array of Objects in Python

As browsers can swiftly parse JSON objects, they help transfer data between a client and a server. This article will describe how to transmit and receive JSON data using Python’s JSON module.

Читайте также:  Питон принт перенос строки

JavaScript Object Notation

JSON ( JavaScript Object Notation ) is a syntax for data exchange that is simple to read and write by people, simple to parse and produce by computers and store data as well.

It is a full-text format that is unbiased toward language. In addition, python includes a library named json that we can use to interact with JSON data.

JSON’s syntax is regarded as a part of JavaScript’s syntax, which also includes name and value as name is preceded by a colon ( : ) in the representation of data, and name: value pairs are split by comma.

Objects are in curly brackets, while array elements live in square brackets where a comma separates each value. Python will need some JSON to work with before you begin to parse JSON.

There are a few things we must initially set up. Make a Python file first that will contain the code for these exercises. Then, import the JSON module within the file.

JSON Objects in Python

As browsers can swiftly parse JSON objects, they help transfer data between a client and a server. Strings, integers (floats or ints), Boolean values, lists, null, or another JSON object all are acceptable values for JSON object keys.

Here in the below example, an object json_string is created which is populated by a dictionary, the data in the object will be parsed by using the json.load() method and then printing the data shown in the output.

import json json_string = """   "Student":   "ID" : "3",  "name": "kelvin",  "Group": "A",  "Program" : "BSSE"  > > """ data = json.loads(json_string) print (data) 

Источник

Python JSON to List

To convert a JSON String to Python List, use json.loads() function. loads() function takes JSON Array string as argument and returns a Python List.

Syntax

The syntax to use json.loads() method is

import json aList = json.dumps(jsonString)

We have to import json package to use json.dumps() function.

Note: Please note that dumps() function returns a Python List, only if the JSON string is a JSON Array.

Examples

1. Convert JSON array string to Python list

In this example, we will take a JSON Array string and convert it into Python List. The JSON Array has two elements, with each element containing two key:value pairs of each.

After loading the JSON string to list, we shall print the value for key “b”.

Python Program

import json jsonStr = '[, ]' aList = json.loads(jsonStr) print(aList[0]['b'])

2. Convert JSON array of arrays string to Python list

In this example, we will take a JSON String with Array of Arrays and convert it to Python List of Lists.

After parsing the JSON string to Python List, we shall access the first element of first first in the whole list.

Python Program

import json jsonStr = '[[], []]' aList = json.loads(jsonStr) print(aList[0][0])

Summary

In this Python JSON Tutorial, we learned how to load a JSON Array string to Python List.

Источник

Оцените статью