-3

I am very much new to JSON parsing. Below is my JSON:

[
    {
        "description": "Newton", 
        "exam_code": {
            "date_added": "2015-05-13T04:49:54+00:00", 
            "description": "Production", 
            "exam_tags": [
                {
                    "date_added": "2012-01-13T03:39:17+00:00", 
                    "descriptive_name": "Production v0.1", 
                    "id": 1, 
                    "max_count": "147", 
                    "name": "Production"
                }
            ], 
            "id": 1, 
            "name": "Production", 
            "prefix": "SA"
        }, 
        "name": "CM"
    }, 
    {
        "description": "Opera", 
        "exam_code": {
            "date_added": "2015-05-13T04:49:54+00:00", 
            "description": "Production", 
            "test_tags": [
                {
                    "date_added": "2012-02-22T12:44:55+00:00", 
                    "descriptive_name": "Production v0.1", 
                    "id": 1, 
                    "max_count": "147", 
                    "name": "Production" 
                }
            ], 
            "id": 1, 
            "name": "Production", 
            "prefix": "SA"
        },       
        "name": "OS"
    }
]

Here I am trying to find if name value is CM print description value.

If name value is OS then print description value.

Please help me to to understand how JSON parsing can be done?

1 Answers1

-1

Considering you have already read the JSON string from somewhere, be it a file, stdin, or any other source.

You can actually deserialize it into a Python object by doing:

import json

# ...

json_data = json.loads(json_str)

Where json_str is the JSON string that you want to parse.

In your case, json_str will get deserialized into a Python list, so you can do any operation on it as you'd normally do with a list.

Of course, this includes iterating over the elements:

for item in json_data:
    if item.get('name') in ('CM', 'OS'):
        print(item['description'])

As you can see, the items in json_data have been deserialized into dict, so you can access the actual fields using dict operations.


Note

You can also deserialize a JSON from the source directly, provided you have access to the file handler/descriptor or stream:

# Loading from a file

import json
with open('my_json.json', 'r') as fd:
    # Note that we're using json.load, not json.loads
    json_data = json.load(fd)

# Loading from stdin

import json, sys
json_data = json.load(sys.stdin)
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154