Add Element to a Json File

How to append data to a json file?

json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.

Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.

Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.

Python add new element to existing JSON File

You need to write the data back to the file:

with open('test.json', 'w') as customerdata:
json.dump(customers_json, customerdata)

Add element to a JSON file?

You can do this.

data[0]['f'] = var

How to append element at the end in json file using python?

Up to Python 3.6, standard dicts were unordered, meaning there was no guarantee that when json was loaded and saved order of keys would remain the same. There was possibility of using from collections import OrderedDict but of course making it work for json.loads wasn't trivial.

Since 3.7, dict objects are guaranteed to keep insertion order, so you can use it to keep the order as in the original file.

How do I add to an existing json file in node.js

If you want the file to be valid JSON, you have to open your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.

var fs = require('fs')

var currentSearchResult = 'example'

fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data)
json.push('search result: ' + currentSearchResult)

fs.writeFile("results.json", JSON.stringify(json))

Python - adding an element to a json file

To add a key to a dict, you simply name it:

your_dict['convID'] = 'convID_value'

So, your code would be something like:

import json

# read a file, or get a string
your_json = '{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message"}'

your_dict = json.loads(your_json)

your_dict['convID'] = 'convID_value'

So, using it with your code, it will be:

def update_json():
json_cache = {}

with open('example.json', 'r') as j:
json_cache = json.load(j)

json_cache['convID'] = 'the value you want'

with open('example.json', 'w') as k:
json.dump(json_cache, f)

Related Topics

Leave a reply