How to Read Json to NumPy Array in Python

Do you want to read Json data and convert its values to NumPy array? If yes then this post is for you. In this tutorial you will know how to read Json to NumPy array in python with steps.

Steps to Read JSON to NumPy array in Python

Let’s know all steps or instructions to read JSON data into a NumPy array in Python.

Step 1: Import Required Libraries

import json
import numpy as np

Step 2: Load JSON Data

If JSON data is a string

# Sample JSON data (replace with your actual JSON data)
json_data = '{"data": [[10, 20, 30], [40, 50, 60], [70, 80, 90]]}'

# Load JSON data
loaded_data = json.loads(json_data)

If JSON data is in a file then use the code below.

# Specify the path to your JSON file
json_file_path = 'path/to/your/file.json'

# Load JSON data from file
with open(json_file_path, 'r') as file:
    loaded_data = json.load(file)

Step 3: Convert to NumPy Array

# Extract the array data from the loaded JSON
array_data = np.array(loaded_data['data'])

# Print or use the NumPy array
print(array_data)

Output

[[10 20 30]
 [40 50 60]
 [70 80 90]]

Replace the sample json_data or json_file_path with your actual JSON data or file path. The key used in loaded_data['data'] should match the structure of your JSON.

Conclusion

Sometimes you have the option to directly convert the data into Numpy array. If the JSON response contains array and wants to perform mathematical calculation then you should convert that array to numpy array. The above were the steps to read json to numpy array in python.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link