您在這裡

Parsing JSON

24 二月, 2015 - 11:24

We construct our JSON by nesting dictionaries (objects) and lists as needed. In this example we represent a list of users where each user is a set of key value pairs (i.e. a dictionary). So we have a list of dictionaries.

In the following program, we use the built-in json library parse the JSON and read through the data. Compare this closely to the equivalent XML data and code above. The JSON has less detail so we must know in advance that we are getting a list, and the list is of users and each user is a set of key value pairs. The JSON is more succinct (an advantage) but also is less self-describing (a disadvantage).

import json

input = '''[    { "id" : "001",      "x" : "2",      "name" : "Chuck"    } ,    { "id" : "009",      "x" : "7",      "name" : "Chuck"    }]'''

info = json.loads(input)print 'User count:', len(info)

for item in info:    print 'Name', item['name']    print 'Id', item['id']    print 'Attribute', item['x']

If you compare the code to extract data from the parsed JSON and XML you will see that what we get from json.loads() is a Python list which we traverse with a for loop and each item within that list is a Python dictionary which we use the Python index operator to extract the various bits of each user. Once the JSON has been parsed - we simply have native Python objects and structures. We don’t have to use the JSON library to dig through the parsed JSON since the returned data is simply native Python structures.

The output of this program is exactly the same as the XML version above.

User count: 2Name ChuckId 001Attribute 2Name BrentId 009Attribute 7

In general, there is an industry trend away from XML and towards JSON for web services. Because the JSON is simpler and more directly maps to native data structures we already have in programming languages, the parsing and data extraction code is usually simpler and more direct when using JSON. But XML is more selfdescriptive than JSON and so there are some applications where XML retains an advantage. For example, most word processors store documents internally using XML rather than JSON.