1

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

2
  • Do you know how to append to a Python object? Then just load the JSON, manipulate the Python object, write out JSON again. Commented Apr 26, 2015 at 2:57
  • Great, sounds simply enough :) Commented Apr 26, 2015 at 2:59

1 Answer 1

3

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.