Use [] to access a dynamic key on the object
json.users[username] = {a: 1, b: 2}
Be careful naming your variable like that tho because json the way you're using it is not JSON. JSON is a string, not an object with keys.
See the below demo for distinction
var json = '{"users":{"test1":{},"test2":{}}}';
var obj = JSON.parse(json);
var newuser = 'test3';
obj.users[newuser] = {};
console.log(JSON.stringify(obj));
//=> {"users":{"test1":{},"test2":{},"test3":{}}}
Answer from Mulan on Stack OverflowInsert json object into existing Json array
Add new attribute (element) to JSON object using JavaScript - Stack Overflow
python - How to append data to a json file? - Stack Overflow
python - How to add data to a already existing json object without overwriting existing data - Stack Overflow
Videos
JSON stands for JavaScript Object Notation. A JSON object is really a string that has yet to be turned into the object it represents.
To add a property to an existing object in JS you could do the following.
object["property"] = value;
or
object.property = value;
If you provide some extra info like exactly what you need to do in context you might get a more tailored answer.
var jsonObj = {
members:
{
host: "hostName",
viewers:
{
user1: "value1",
user2: "value2",
user3: "value3"
}
}
}
for(var i=4; i<=8; i++){
var newUser = "user" + i;
var newValue = "value" + i;
jsonObj.members.viewers[newUser] = newValue ;
}
console.log(jsonObj);
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.
You probably want to use a JSON list instead of a dictionary as the toplevel element.
So, initialize the file with an empty list:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as f:
json.dump([], f)
Then, you can append new entries to this list:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
entry = {'name': args.name, 'url': args.url}
feeds.append(entry)
json.dump(feeds, feedsjson)
Note that this will be slow to execute because you will rewrite the full contents of the file every time you call add. If you are calling it in a loop, consider adding all the feeds to a list in advance, then writing the list out in one go.
If you use json.NET you can simply deserialize and serialize the json.
var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);
list.Add(new Person(1234,"carl2");
var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);
Using Json.Net
//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
var array = JArray.Parse(initialJson);
var itemToAdd = new JObject();
itemToAdd["id"] = 1234;
itemToAdd["name"] = "carl2";
array.Add(itemToAdd);
var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);
//save to file here
Using this method doesn't require strongly typed objects
You could replace this bit:
//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
With
var initialJson = File.ReadAllText(@"c:\myjson.json")
To load the json from a text file
I found the solution, thanks to the comments by other users and to a "retired" answer, not present here anymore. Maybe it was my fault not being clear.
public void addEntryToJsonFile(Context ctx, String id, String name, String size) {
// parse existing/init new JSON
File jsonFile = new File(ctx.getDir("my_data_dir", 0), "my_json_file.json");
String previousJson = null;
if (jsonFile.exists()) {
try {
previousJson = Utils.readFromFile(jsonFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
previousJson = "{}";
}
// create new "complex" object
JSONObject mO = null;
JSONObject jO = new JSONObject();
try {
mO = new JSONObject(previousJson);
jO.put("completed", true);
jO.put("name", name);
jO.put("size", size);
mO.put(id, jO); //thanks "retired" answer
} catch (JSONException e) {
e.printStackTrace();
}
// generate string from the object
String jsonString = null;
try {
jsonString = mO.toString(4);
} catch (JSONException e) {
e.printStackTrace();
}
// write back JSON file
Utils.writeToFile(jsonFile, jsonString);
}
Edited after dentex comment
- Read your file
- Parse the root Json object
- If the root object not is already a complex object
- Create a new root object
- put your root object in it
- put your second object in the root object
- Write bnack your file
in pseudo code:
oldJson = ParseJsonFromFile()
newJson = {"item1": true, "item2": "abcde" ...}
JSONObject root;
if (oldJson.hasKey("pass1") {
root = oldJson
} else {
root = new JSONObject()
root.add("pass1", oldJson)
}
root.add("pass" + root.getSize() + 2, newJson)
WriteJsonToFile(root)