JavaScript and JSON Essentials
上QQ阅读APP看书,第一时间看更新

JSON implementation in Python

Python is a very popular scripting language that is extensively used to perform string operations and to build console applications. It can be used to fetch data from JSON API, and once the JSON data is retrieved it will be treated as JSON string. To perform any operations on that JSON string, Python provides the JSON module. The JSON module is an amalgamation of many powerful functions that we can use to parse the JSON string on hand:

This example is only intended to show you how JSON can be generated using Python.
import json

student = [{
"studentid" : 101,
"firstname" : "John",
"lastname" : "Doe",
## make sure we have first letter capitalize in case of boolean
"isStudent" : True,
"scores" : [40, 50],
"courses" : {
"major" : "Finance",
"minor" : "Marketing"
}
}]

print json.dumps(student)

In this example we have used complex datatypes, such as Tuples and Dictionaries, to store the scores and courses respectively; since this is not a Python course, we will not go into those datatypes in any depth.

To run this script, Python2 needs to be installed. It comes preinstalled on any *nix operating system. Play with our code in Python with the following online executor:  https://www.jdoodle.com/python-programming-online.

The output is as follows:

[{"studentid": 101, "firstname": "John", "lastname": "Doe", "isStudent": true, "courses": {"major": "Finance", "minor": "Marketing"}, "scores": [40, 50]}]

The keys might get rearranged based on the datatype; we can use the sort_keys flag to retrieve the original order.

Now, let us take a quick look at how the JSON decoding is performed in Python:

This example is only intended to show you how JSON can be ingested into Python.
student_json = '''[{"studentid": 101, "firstname": "John", "lastname": "Doe", "isStudent": true, "courses": {"major": "Finance", "minor": "Marketing"}, "scores": [40, 50]}]'''

print json.loads(student_json)

In this example, we are storing the JSON string in student_json, and we are using the json.loads() method that is available through the JSON module in Python.

The output is as follows:

[
{
u 'studentid': 101,
u 'firstname': u 'John',
u 'lastname': u 'Doe',
u 'isStudent': True,
u 'courses':
{
u 'major': u 'Finance',
u 'minor': u 'Marketing'
},
u 'scores': [40, 50]
}]