'How do I convert a numpy array filled with strings to json

n=int(input('n='))    
array = np.empty(shape= 
[n,4],dtype='|S10')
.
.
.
.
array= array.tolist()
array =[[b'1',b'1/1/1',b'1',b'1']]
dump(array,json_file)

I got an error: Object of type bytes is not JSON serializable



Solution 1:[1]

Why you type 'b' before the strings ?

Your code is not complete, I modified it to let it work:

import numpy as np
import json

n=int(input('n=')) 
array = np.empty(shape=[n,4],dtype='|S10')
array = [['1', '1/1/1', '1', '1']]
with open('test.json', 'w') as json_file:
    json.dump(array, json_file)

That if you want your current code to work, if you want to serialize a numpy array of strings you must use 'U1' dtype and then convert it to list, like this:

import numpy as np
import json

n = int(input('n=')) 
array = np.empty(shape=[n,4], dtype='U1')
array = array.tolist()
with open('test.json', 'w') as json_file:
    json.dump(array, json_file)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1