DEV Community

loading...

Why Python Json Dumps

sdonkoh1 profile image sdonkoh1 ・1 min read

Json dumps can be used to take a Python data structure(list,tuple,dictionary,set) and generate a string in JSON format. That string can then be saved in a file, inserted in a database, or sent over the wire.

Example 1:

import json

details = {
    "FirstName":"Nana",
    "LastName":"Kwame",
    "Email":"None",
    "Children":"None"
}
print(details)

json_str = json.dumps(details)

with open('data.json','w') as fh:
    fh.write(json_str)
Enter fullscreen mode Exit fullscreen mode

Example 2:

import json

details = {
    "FirstName":"Nana",
    "LastName":"Kwame",
    "Email":"None",
    "Children":"None"
}

with open('data.json','w') as fh:
        json.dump(a,fh)
Enter fullscreen mode Exit fullscreen mode

Loading Json Dumps

Example 1:

import json

with open('data.json') as fh:
    json_str = fh.read()

print(json_str)
Enter fullscreen mode Exit fullscreen mode

Example 2:

import json

with open('data.json','r') as fh:
    a = json.load(fh)

print(a)
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide