Parse json data in Python

The json library can parse JSON from strings or files. This library parses JSON and converts it to a Python dictionary or list. It can also convert Python dictionaries or lists to JSON strings.

parsing JSON

Create the following string containing the JSON data

1

json_string = '{"first_name": "Guido", "last_name":"Rossum"}'

It can be parsed like this:

1

2

import json

parsed_json = json.loads(json_string)

It can then be used like a regular dictionary:

1

2

print(parsed_json['first_name'])

"Guido"

You can convert the following object to JSON:

1

2

3

4

5

6

7

= {

    'first_name''Guido',

    'second_name''Rossum',

    'titles': ['BDFL''Developer'],

}

print(json.dumps(d))

'{"first_name": "Guido", "last_name": "Rossum", "titles": ["BDFL", "Developer"]}'

simplejson

The JSON library was added in version 2.6 of Python. If you use an earlier version of Python, the simplejson library is available via PyPI.

simplejson is similar to the json standard library, which enables developers using older versions of Python to use the latest features in the json library.

If the json library is not available, you can alias simplejson to json:

1

import simplejson as json

After importing simplejson as json, the above example will work as if you were using the standard json library.

Guess you like

Origin blog.csdn.net/Merissa_/article/details/129588442