w3resource

How to read numeric data from a JSON file into a NumPy array?


NumPy: I/O Operations Exercise-13 with Solution


Write a NumPy program that reads data from a JSON file into a NumPy array. The JSON file contains numeric data.

Content of sample.json
-----------------------------
{
    "Title": "The Cuckoo's Calling",
    "Author": "Robert Galbraith",
    "Genre": "classic crime novel",
    "Detail": {
        "Publisher": "Little Brown",
        "Publication_Year": 2013,
        "ISBN-13": 9781408704004,
        "Language": "English",
        "Pages": 494
    },
    "Price": [
        {
            "type": "Hardcover",
            "price": 16.65
        },
        {
            "type": "Kidle Edition",
            "price": 7.03
        }
    ]
}

Sample Solution:

Python Code:

import numpy as np
import json

# Define the path to the JSON file
json_file_path = 'sample.json'

# Read the JSON file into a Python list
with open(json_file_path, 'r') as json_file:
    data_list = json.load(json_file)

# Convert the list to a NumPy array
data_array = np.array(data_list)

# Print the NumPy array
print(data_array)

Output:

{'Title': "The Cuckoo's Calling", 'Author': 'Robert Galbraith', 'Genre': 'classic crime novel', 'Detail': {'Publisher': 'Little Brown', 'Publication_Year': 2013, 'ISBN-13': 9781408704004, 'Language': 'English', 'Pages': 494}, 'Price': [{'type': 'Hardcover', 'price': 16.65}, {'type': 'Kidle Edition', 'price': 7.03}]}

Explanation:

  • Import NumPy and JSON Libraries: Import the NumPy and JSON libraries to handle arrays and JSON data.
  • Define JSON File Path: Specify the path to the JSON file containing the numeric data.
  • Read JSON File into Python List: Open and read the JSON file using json.load() to load the contents into a Python list.
  • Convert List to NumPy Array: Use np.array() to convert the Python list to a NumPy array.
  • Finally print the resulting NumPy array to verify the data read from the JSON file.

Python-Numpy Code Editor: