Convert NumPy array to JSON Python(5ways)

In this post, we are going to learn to Convert NumPy array to JSON Python with examples.We will use the JSON module that is imported using “import JSON“, First need to make sure the JSON module is installed or we can install it using “pip install jsonlib-python3” .NumPy land Pandas Library.

1. Convert NumPy array to JSON Python


In this Python exmple we are converting a Numpy array to JSON and storing it into JSON file.We have First converted NumPy array to list using tolist() method and iterate over the list using list comprehension along with enumerate() function.The data returned by list comprehension is used to write into JSON file using json.dump(data, Fileobj) method.

import numpy as np

import json
 
myarr = np.array([['Jack', 7, 44], ['rack', 13, 35], ['Sham', 13, 35]])
lists = myarr.tolist()
data = [{'Name': item[0], 'Age': item[1], 'Data': item[2]} for i, item in enumerate(lists)]
print(data)

with open('myJsonfile', 'w') as FileObj:
    json.dump(data, Fileobj)

Output

[{'Name': 'Jack', 'Age': '7', 'Data': '44'}, {'Name': 'rack', 'Age': '13', 'Data': '35'}, {'Name': 'Sham', 'Age': '13', 'Data': '35'}]

2. Convert NumPy array to JSON Python


In this Python Program,We have define a NumpyEncoder(), The first parameter to json.dump() is Numpy array(myarr) and Second parameter is and we assign NumpyEncoder function to default=NumpyEncoder..Let us understand with Example

import json
import numpy as np

myarr = np.array([['Jack', 7, 44],['rack', 13, 35],['Sham', 13, 35]])
class NumpyEncoder(json.JSONEncoder):
   
    def default(self, myobj):
        if isinstance(myobj, np.integer):
            return int(myobjobj)
        elif isinstance(myobj, np.floating):
            return float(myobj)
        elif isinstance(myobj, np.ndarray):
            return myobj.tolist()
        return json.JSONEncoder.default(self, myobj)

numpytoJson = json.dumps(myarr, cls=NumpyEncoder)
print(numpytoJson)

#reading JSON data
JSONToNUmpy = json.loads(numpytoJson)



print('JSON to NUmpy:',JSONToNUmpy)

Output

[["Jack", "7", "44"], ["rack", "13", "35"], ["Sham", "13", "35"]]
JSON to NUmpy [['Jack', '7', '44'], ['rack', '13', '35'], ['Sham', '13', '35']]

3. Pandas to Convert NumPy array to JSON Python


We have Used Pandas libaray to_Json() method to convert NumPy array to JSON.First we have created a dataframe from NumPy array with Index and columns and use dataframe object to call the to_json() method with parameter orient=’index’

import pandas as pd
import numpy

myarr = np.array([['Jack', 7, 44],['rack', 13, 35],['Sham', 13, 35]])

dfobj = pd.DataFrame(myarr, index=['row 1', 'row 2','row 3'], columns=['Name', 'Age', 'Data'])
dfobj = dfobj.to_json(orient='index')

print("NumPy array to Json:")
print(dfobj)

Output

NumPy array to Json:
{"row 1":{"Name":"Jack","Age":"7","Data":"44"},"row 2":{"Name":"rack","Age":"13","Data":"35"},"row 3":{"Name":"Sham","Age":"13","Data":"35"}}

4. Pandas Convert NumPy array to JSON orient by Values


We have Used Pandas libaray to_Json() method to convert NumPy array to JSON.First we have created a dataframe from NumPy array with Index and columns and use dataframe object to call the to_json() method with parameter orient=’Values’ instead of index

import pandas as pd
import numpy

myarr = np.array([['Jack', 7, 44],['rack', 13, 35],['Sham', 13, 35]])

dfobj = pd.DataFrame(myarr, index=['row 1', 'row 2','row 3'], columns=['Name', 'Age', 'Data'])
dfobj = dfobj.to_json(orient='values')

print("NumPy array to Json:")
print(dfobj)

Output

NumPy array to Json:
[["Jack","7","44"],["rack","13","35"],["Sham","13","35"]]

5. Pandas Convert NumPy array to JSON orient by Values


In this Python program example, We have used Pandas Library, First, we have installed it on the local system and imported using “”.We have Used the Pandas library to_Json() method to convert the NumPy array to JSON. First, we have created a data frame from NumPy array with Index and columns and use data frame object to call the to_json() method with parameter orient=’split’ instead of index and values

import pandas as pd
import numpy
myarr = np.array([['Jack', 7, 44],['rack', 13, 35],['Sham', 13, 35]])

dfobj = pd.DataFrame(myarr, index=['row 1', 'row 2','row 3'], columns=['Name', 'Age', 'Data'])
dfobj = dfobj.to_json(orient='split')

print("NumPy array to Json:")
print(dfobj)

Output

NumPy array to Json:
{"columns":["Name","Age","Data"],"index":["row 1","row 2","row 3"],"data":[["Jack","7","44"],["rack","13","35"],["Sham","13","35"]]}

Summary

In this post, we have learned how to Convert the NumPy array to JSON Python by using the JSON module, NumPy, and Pandas.