Please help.. writing JSON

Hello all. I am so stuck trying to write my data into a JSON file I am literally crying. I have 100 text files with three columns, a, b, and c, each containing a set number of measurements. I would like to assign each file an ID, a random number really, as well as a string that's either "X" or "Y". I would like to save the ID and string, as well as all the measurements from the columns. I tried making an array of ID and string to be the same size as the measurements, and then pass them to a dictionary:

dict = {"ID": [], "STRING": [], "col_a": [], "col_b": [], "col_c: []}

This doesn't work, it gives me an error telling me that "{} is not JSON serializable". Any help is much-appreciated thank you

Posted Aug 10, 2017, 7:15 PM UTC

05

Post your code.

1
programmer1853OP•

Here it is, sorry!

1
programmer1853OP•
dict = {"ID": [], "STRING": [], "col_a": [], "col_b": [], "col_c: []}

for file_name in files:
    data = np.loadtxt(file_name):
    a = data[:,0] #these columns are lists
    b = data[:,1]
    c = data[:,2]

    num = np.random.uniform(0, 360, 1)
    string = "X"

    dict['ID'].append(num)
    dict['STRING'].append(string)
    dict['col_a'].append(a)
    dict['col_b'].append(b)
    dict['col_c'].append(c)

with open('json_file.json', 'w') as outfile:
    json.dump(dict, outfile)
1
Username_RANDINT•

There's a syntax error first, you don't close the string properly of col_c in the dictionary. There's also a colon on line 4 that shouldn't be there.

Errors in the line of "not JSON serializable" means you have some kind of type that JSON can't handle. So my first guess is those numpy values are causing trouble and you'll have to convert them first to something JSON understands.

Edit: the documentation has a list of all accepted types.

2
efmccurdy•

The standard advise when writing numpy arrays to json is to first use the numpy.ndarray.tolist function to convert the array into json compatable lists.

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html#numpy-ndarray-tolist

1