Jonty Morris
Jonty Morris

Reputation: 807

Python writing to a json

Ive been working on an address book in python, and I need to make a function that can write to a json file. The function needs to be able to add/append to this specific json layout

Json Layout Example -

{"addresses":

        [
          {"name": "example", "town": "example", "address": "example"}
        ]

}

The Problem - I only know how to write to a json file, not how to write to a json object...

Can someone please show me an example of how to add/append to a json object

Upvotes: 1

Views: 125

Answers (1)

Colton Allen
Colton Allen

Reputation: 3060

JSON is just a string in Python. You can load and dump the json whenever you need to return it or change it respectively. For example:

import json


py_dict = {'a': 'b'}
# Convert dict to string
json_obj = json.dumps(py_dict)
# oops need to make a change -> convert from string to dict
py_dict = json.loads(json_obj)
# append to dict
py_dict['hello'] = 'world'
# Convert dict to string
json_obj = json.dumps(py_dict)

Upvotes: 3

Related Questions