0

The question is very self explanatory. I need to write or append at a specific key/value of an object in json via python.

I'm not sure how to do it because I'm not good with JSON but here is an example of how I tried to do it (I know it is wrong).

with open('info.json', 'a') as f:
    json.dumps(data, ['key1'])

this is the json file:

{"key0":"[email protected]","key1":"12345678"}
2
  • What are you trying to do with the JSON file? What does your desired output look like? Commented Oct 4, 2020 at 22:18
  • suppose data="random string" then json would be: {"key0":"[email protected]","key1":"12345678random string"} Commented Oct 4, 2020 at 22:22

2 Answers 2

1

A typical usage pattern for JSONs in Python is to load the JSON object into Python, edit that object, and then write the resulting object back out to file.

import json

with open('info.json', 'r') as infile:
    my_data = json.load(infile)
    
my_data['key1'] = my_data['key1'] + 'random string'
# perform other alterations to my_data here, as appropriate ...

with open('scratch.json', 'w') as outfile:
    json.dump(my_data, outfile)

Contents of 'info.json' are now

{"key0": "[email protected]", "key1": "12345678random string"}

The key operations were json.load(fp), which deserialized the file into a Python object in memory, and json.dump(obj, fp), which reserialized the edited object to the file being written out.

This may be unsuitable if you're editing very large JSON objects and cannot easily pull the entire object into memory at once, but if you're just trying to learn the basics of Python's JSON library it should help you get started.

Sign up to request clarification or add additional context in comments.

Comments

0

An example for appending data to a json file using json library:

import json

raw =  '{ "color": "green",  "type": "car" }'
data_to_add = { "gear": "manual" }  
parsed = json.loads(raw) 
parsed.update(data_to_add) 

You can then save your changes with json.dumps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.