2016/11/22

What is the difference between json.dumps and json.loads?

This post is about the difference between json.dumps and json.loads.

JSON.DUMPS - takes an json object and produces a string.

Python Script



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import json
 
my_dictionary = {
    "key 1": "Value 1",
    "key 2": "Value 2",
    "decimal": 100,
    "boolean": False,
    "list": [1, 2, 3],
    "dict": {
        "child key 1": "value 1",
        "child key 2": "value 2"
    }
}

# accessing the content in the my_dictionary object
print("**Object**")
print(my_dictionary["key 1"])
print(my_dictionary["list"])
print(my_dictionary["dict"])

li = my_dictionary["list"]
print(li[0])

dic = my_dictionary["dict"]
print(dic["child key 1"])

print("")

# dumps takes an object and produces a string
print("**String**")
print(json.dumps(my_dictionary, indent=4))

print("")
jd = json.dumps(my_dictionary)
print(jd[0])
print(jd[1])
print(jd[2])

Result


--------------------------------------------------------------------------------------------------------------------------

JSON.LOADS takes a file-like object, reads the data from that object, and use that string to create a json object.

Python Script


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import json
 
# json_data is a string object
json_data = """ {
    "key 1": "value 1",
    "key 2": "value 2",
    "decimal": 10,
    "boolean": true,
    "list": [1, 2, 3],
    "dictionary": {
        "child key 1": "child value 1",
        "child key 2": "child value 2"
    }
}"""

print(json_data)
print(json_data[8])
print(json_data[9])
print(json_data[10])
print(json_data[11])
print(json_data[12])
print("")

print("Convert the string object to JSON object using json.loads") 
my_dict = json.loads(json_data)

print("string value: %s" % my_dict["key 1"])
print("decimal value: %d" % my_dict["decimal"])
print("decimal value: %r" % my_dict["boolean"])
print("list values: %s" % my_dict["list"])
print("dictionary: %s" % my_dict["dictionary"]["child key 2"])

Result


Reference:

What is the difference between json.dumps and json.load?
http://stackoverflow.com/questions/32911336/what-is-the-difference-between-json-dumps-and-json-load

Python dictionaries and JSON (crash course)
https://codingnetworker.com/2015/10/python-dictionaries-json-crash-course/

No comments:

Post a Comment