简体   繁体   中英

How to format JSON to display “Class”, “Score” and their values?

I'm using IBM's Watson Visual Recognition API and I'm trying to format the output JSON data to display only the "Class","Score" and both of their values

I've used

print(json.dumps(classes_result, indent=2))

to get the output:

  "images": [
    {
      "classifiers": [
        {
          "classifier_id": "default",
          "name": "default",
          "classes": [
            {
              "class": "honey buzzard",
              "score": 0.639,
              "type_hierarchy": "/animal/bird/bird of prey/hawk/honey buzzard"
            },
            {
              "class": "hawk",
              "score": 0.891
            },
            {
              "class": "bird of prey",
              "score": 0.918
            },

Try this, with nested loops over your dict:

for image in images:
    classifiers = image['classifiers']
    for classifier in classifiers: 
        classes = classifier['classes']
        for _class in classes: 
            class_value = _class['class']
            score_value = _class['score']
            print(class_value, score_value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM