0

I have a list of objects in this format as below. I wanted to save it in a json file format.

{'result': [{'topleft': {'y': 103, 'x': 187}, 'confidence': 0.833129, 'bottomright': {'y': 375, 'x': 271}, 'label': 'person'}]}

I was able to print the objects as above. But, when I try to save it in JSON format. I encounter error "raise TypeError(repr(o) + " is not JSON serializable")"

Here's part of my code:

def writeToJSONFile(data):
    filePathNameWExt = '/media/test/abc.json'
    with open(filePathNameWExt, 'w') as fp:
        json.dump(data, fp)

result = tfnet.return_predict(img)
data['result']=result
print (data)   
writeToJSONFile(data)
  • when i set result to the json string you post above, I can execute the script properly, what is tfnet.return_predict(img) return – LiQIang.Feng Feb 07 '18 at 09:14
  • it returns `[{'topleft': {'y': 103, 'x': 187}, 'confidence': 0.833129, 'bottomright': {'y': 375, 'x': 271}, 'label': 'person'}]` –  Feb 08 '18 at 09:02

1 Answers1

0

I think your issue is that the type you are using for floating points is not JSON serializable. If you don't want to got through the hassle of making it serializable, you can simply convert it to "regular" floats before serializing.

For example, if you are using numpy floats (numpy.floating), you could do something like this:

result = tfnet.return_predict(img)

# Hack: Convert any numpy floats in result to regular floats.
# The lambda takes a (key,value) tuple and returns (key, float(value)), for any
# values that are numpy floats, without modifiying other values.
# The map applies the lambda to all (key,value) tuples in result.items().
serializable_result = dict(map(lambda (k, v): (k, float(v) if isinstance(v, numpy.floating) else v), result.items()))

data['result']=serializable_result 
print (data)   
writeToJSONFile(data)

The precise code above might not work for your specific objects, but the general idea is simply to convert any non "standard" floats to standard serializable floats before serializing.

Yoni Rabinovitch
  • 5,171
  • 1
  • 23
  • 34