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:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy array to an Excel file and read it back
Next: How to write a NumPy array with numeric data to a JSON file?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/read-numeric-data-from-a-json-file-into-a-numpy-array.php