How to read numeric data from a JSON file into a NumPy array?
13. JSON File Read to Array
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.
For more Practice: Solve these Related Problems:
- Write a Numpy program to read a JSON file containing numeric arrays and then merge them into a single NumPy array.
- Write a Numpy program to import JSON data with nested numeric structures into a NumPy array and flatten the hierarchy.
- Write a Numpy program to convert a JSON file with numeric data into a structured array and then perform field-specific operations.
- Write a Numpy program to read a JSON file into a NumPy array and then apply a custom function to normalize the data.
Go to:
PREV : Excel File Read/Write via Pandas.
NEXT : Numeric Array Write to JSON.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
