Python for json array

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.

Читайте также:  Debian buster php 8

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.

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.

Источник

Python for json array

Last updated: Feb 23, 2023
Reading time · 4 min

banner

# Table of Contents

# How to filter a JSON array in Python

To filter a JSON array in Python:

  1. Use the json.loads() method to convert the JSON array to a Python list.
  2. Use a list comprehension to iterate over the list.
  3. Check if each item in the list meets a certain condition and return the result.
Copied!
import json json_array = json.dumps( [ 'name': 'Alice', 'salary': 100>, 'name': 'Bobby', 'salary': 50>, 'name': 'Carl', 'salary': 75> ] ) a_list = json.loads(json_array) filtered_list = [ dictionary for dictionary in a_list if dictionary['salary'] > 50 ] # 👇️ [, ] print(filtered_list)

filter json array

The json.dumps method converts a Python object to a JSON formatted string.

Conversely, the json.loads method parses a JSON string into a native Python object.

We then used a list comprehension to iterate over the list.

On each iteration, we check if a certain condition is met and return the result.

The code sample checks if each dictionary has a salary key with a value greater than 50 .

Copied!
import json json_array = json.dumps( [ 'name': 'Alice', 'salary': 100>, 'name': 'Bobby', 'salary': 50>, 'name': 'Carl', 'salary': 75> ] ) a_list = json.loads(json_array) filtered_list = [ dictionary for dictionary in a_list if dictionary['salary'] > 50 ] # 👇️ [, ] print(filtered_list)

The new list only contains the dictionaries that meet the condition.

You can use this approach to check for any condition.

Alternatively, you can use a for loop.

# How to filter a JSON array using a for loop

This is a four-step process:

  1. Use the json.loads() method to convert the JSON array to a Python list.
  2. Use a for loop to iterate over the list.
  3. Check if each list item meets a certain condition.
  4. Append the matching items to a new list.
Copied!
import json json_array = json.dumps( [ 'name': 'Alice', 'salary': 100>, 'name': 'Bobby', 'salary': 50>, 'name': 'Carl', 'salary': 75> ] ) a_list = json.loads(json_array) filtered_list = [] for dictionary in a_list: if dictionary['salary'] > 50: filtered_list.append(dictionary) # 👇️ [, ] print(filtered_list)

filter json array using for loop

We used a for loop to iterate over the list.

On each iteration, we check if the current dictionary has a salary key with a value greater than 50 .

If the condition is met, we use the list.append() method to append the dictionary to a new list.

The list.append() method adds an item to the end of the list.

The new list only contains the items of the original list that meet the condition.

You can use the same approach to filter a JSON array stored in a file.

# Filter a JSON array that is stored in a file in Python

To filter a JSON array that is stored in a file:

  1. Open the JSON file in reading mode.
  2. Use the JSON.load() method to deserialize the file to a Python list.
  3. Use a list comprehension to filter the list.
Copied!
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: a_list = json.load(f) # 👇️ [, , ] print(a_list) filtered_list = [ dictionary for dictionary in a_list if dictionary['salary'] > 50 ] # 👇️ [, ] print(filtered_list)

The code sample assumes that you have an example.json file stored in the same directory as your main.py script.

Copied!
[ "name": "Alice", "salary": 100>, "name": "Bobby", "salary": 50>, "name": "Carl", "salary": 75> ]

filter json array that is stored in file

The json.load method is used to deserialize a file to a Python object.

On the other hand, the json.loads method is used to deserialize a JSON string to a Python object.

The json.load() method expects a text file or a binary file containing a JSON document that implements a .read() method.

Once we have the data from the JSON file parsed to a native Python list, we can use a list comprehension or a for loop to filter the list.

You can also use the filter() function to filter a JSON array.

# Filter a JSON array using the filter() function

This is a three-step process:

  1. Use the json.loads() function to parse the JSON array into a Python list.
  2. Pass a lambda function and the list to the filter() function.
  3. The lambda function should check if each list item meets a condition.
Copied!
import json json_array = json.dumps( [ 'name': 'Alice', 'salary': 100>, 'name': 'Bobby', 'salary': 50>, 'name': 'Carl', 'salary': 75> ] ) a_list = json.loads(json_array) filtered_list = list( filter( lambda dictionary: dictionary['salary'] > 50, a_list ) ) # 👇️ [, ] print(filtered_list)

filter json array using filter function

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The function checks if the dictionary meets a certain condition and returns the result.

The last step is to use the list() class to convert the filter object to a list.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • How to Convert JSON NULL values to None using Python
  • How to convert a Tuple to JSON in Python
  • How to Delete a JSON object from a List in Python
  • ImportError: cannot import name ‘json’ from ‘itsdangerous’
  • ValueError: malformed node or string in Python [Solved]
  • Check the syntax of a Python script without executing it
  • Mock multiple return values in a Python unit Test
  • Python: Assert that Mock was called with specific Arguments
  • Python: Sending multipart/form-data request with requests
  • Python: Don’t run a module’s code when it is imported
  • How to keep a Python script output Window open
  • How to merge multiple JSON files in Python [3 Ways]

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Loop through a JSON array in Python

First, we will understand the JSON array and then loop through it in Python.

So what is a JSON array? A JSON array is the Python list of key: value pair which is ordered in nature. So JSON array is just a Python dictionary containing an ordered list of key: value pair. JSON array can be any data type. It can store String, Integer, and other data types as well.

A JSON array is also indexed which means we can access the data inside the array by using an index value. A JSON array is enclosed in [] square brackets and values inside the array are separated by comma(,).

Creating JSON Array and Object

We can create JSON Array and Objects from the Python list and dictionary. For creating a JSON array of strings we can use curly brackets<> with single quotes as shown in the below Python code.

And for making a JSON object we can use the “json.loads()” function in the Python after importing the “json” library into the Python program also shown in the following Python code below.

Looping through a JSON array

We use For Loop function to iterate through a JSON array after creating it. We first, import the json library by using the import function and then create a function using def keyword.

After initializing the function we create a JSON array by using a single quote with curly brackets<>. We then provide the key: value pair to it. After creating a JSON array we then convert it into JSON objects using the json.loads() function.

Now, JSON array has been created and we can use traditional For Loop to loop inside the JSON array and print it’s either key or value or we can also print (key: value pair) both.

Refer to the below Python code to loop through a JSON array:

import json def main(): # creating JSON array j_String = '' # changing JSON string into a JSON object j_Object = json.loads(j_String) # printing keys and values for i in j_Object: value = j_Object[i] print("Key and Value pair are (<>) = (<>)".format(i, value)) pass if __name__ == '__main__': main()
Key and Value pair are (Gaurav) = (Pro-Coder) Key and Value pair are (Car) = (Ferrari) Key and Value pair are (Home) = (Seattle)

You can also refer to this link Python JSON Encoder and Decoder for more understanding of JSON encoding and decoding in Python.

Источник

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