w3resource

How to write a NumPy array with numeric data to a JSON file?

NumPy: I/O Operations Exercise-14 with Solution

Write a NumPy array with numeric data to a JSON file.

Sample Solution:

Python Code:

import numpy as np
import json

# Create a NumPy array with numeric data
data_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

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

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

# Write the Python list to a JSON file
with open(json_file_path, 'w') as json_file:
    json.dump(data_list, json_file)

# Print a message indicating the JSON file has been written
print(f"Data has been written to {json_file_path}")

Output:

Data has been written to data.json

Explanation:

  • Import NumPy and JSON Libraries: Import the NumPy and JSON libraries to handle arrays and JSON data.
  • Create NumPy Array: Define a NumPy array with numeric data.
  • Convert Array to List: Use the tolist() method to convert the NumPy array to a Python list because JSON format supports lists but not NumPy arrays directly.
  • Define JSON File Path: Specify the path where the JSON file will be saved.
  • Write List to JSON File: Open the JSON file in write mode using open(), then use json.dump() to write the Python list to the JSON file.
  • Finally output a message indicating that the data has been successfully written to the JSON file.

Python-Numpy Code Editor:

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

Previous: How to read numeric data from a JSON file into a NumPy array?
Next: Read data from a CSV file into a Pandas DataFrame and convert to NumPy array

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.