2

I'm trying to output the results from my script to JSON. I'm no doubt missing something simple but I'm still learning python. I've imported json at the top of the script. Any pointers in the right direction appreciated.

top_k = results.argsort()[-5:][::-1]
labels = load_labels(label_file)

template = '"{}":"{:0.5f}"'
a=[]

for i in top_k:
    a.append(template.format(labels[i], results[i]))
y = json.dumps(a)
print(y)

Current output is just one long array.

webwurst
  • 4,830
  • 3
  • 23
  • 32
  • in your code, you never write to a file, you just assign it to a variable. Check out the info here for a better idea https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/ – SuperStew Mar 04 '19 at 22:06
  • What output were you expecting/ hoping for? Do you know what JSON is? – nathan.medz Mar 04 '19 at 22:08
  • @nathan.medz hi yeah I'm hoping for an array of objects with key value pairs. so as i have in my template {} would hold the label (key) and {:0.5f} should hold the result (value) – Cherelle Newman Mar 04 '19 at 22:10
  • I should also add that the printed output is then passed over to a node application and then fed to a front end react application. – Cherelle Newman Mar 04 '19 at 22:11

2 Answers2

0

Looks like json.dumps doesn't do what you think it does. json.dumps just puts it into a format that can be easily passed between applications (basically turns it into a string). To turn your output into a dictionary which is what it seems you want you need to change your logic a bit.

top_k = results.argsort()[-5:][::-1]
labels = load_labels(label_file)

out_dict = {}

for i in top_k:
  out_dict[labels[i]] = results[i]

y = json.dumps(out_dict)
print(y)`
nathan.medz
  • 1,595
  • 11
  • 21
  • Thank you so much for the reply and suggestion. I tried that but it returned `TypeError: Object of type 'float32' is not JSON serializable` I then tried to wrap json.dumps(str(out_dict)) to convert it to a string, but it just gave me a long array again instead of an array of objects – Cherelle Newman Mar 04 '19 at 22:20
  • 1
    @CherelleNewman sounds like you're using some custom classes from numpy which the json module doesnt know how to serialize. You can either cast them to a json serializable datatype (in this case float) before adding to your dictionary or you can look https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable for a more robust solution – nathan.medz Mar 04 '19 at 22:23
0

I'm no python expert, but from what I understand is that python treats json object as an dictionary. So if you have your result already as a dictionary object, you can directly return it or save it out to file, you don't want to call dumps in this case. Only do it if you need to pass it to certain function that's expecting a string, then in that case you want to call dumps on the json object/dictionary. Hope that make some sense.

noobius
  • 1,529
  • 7
  • 14