How to Add Multiple Values in Json Object and Get an Updated Json File

How to add multiple values in JSON object and get an updated json file

You can use .hasOwnProperty on that object to find out which object don't have property gender and iteratively add it and write back into the file again!

Here's a code snippet to help you get started.

const fs = require('fs');
const util = require('util');

// Promisify fs api(s)
const readFileAsync = util.promisify(fs.readFile);
const writeFileAsync = util.promisify(fs.writeFile);

// IIFE to read the file, find the objects which has missing properties, add them and write them back
(async function() {
try {
const fileContents = await readFileAsync('data.json');
const fileData = JSON.parse(fileContents);

const remainingData = fileData.filter(x => !x.hasOwnProperty('gender'));

remainingData.forEach(x => x.gender = 'Male');

await writeFileAsync('data.json', JSON.stringify(fileData, null, 4));

} catch(err) {
console.log(`Failed because: {err}!`)

How to modify the multiple values in the JSON file using python

The code works as expected if you have resolved the variable name difference.

Further, I would also suggest to open the file using context manager with so that it gets closed automagically when the with block is exited.

import json, os
with open(".\example.json", 'r') as f:
data = json.load(f)

for feature in data['images']:
feature['file_name'] = os.path.basename(feature["file_name"])



Data in json file:

{'images': [{'id': 1, 'file_name': 'Folder1/Folder2/Folder3/Folder4/1110.jpg', 'height': 3024, 'width': 4032}, {'id': 2, 'file_name': 'Folder1/Folder2/Folder3/Folder4/1111.jpg', 'height': 3024, 'width': 4032}, {'id': 3, 'file_name': 'Folder1/Folder2/Folder3/Folder4/1112.jpg', 'height': 3024, 'width': 4032}]}

Formatted data:

{'images': [{'id': 1, 'file_name': '1110.jpg', 'height': 3024, 'width': 4032}, {'id': 2, 'file_name': '1111.jpg', 'height': 3024, 'width': 4032}, {'id': 3, 'file_name': '1112.jpg', 'height': 3024, 'width': 4032}]}

How to create array of JSON objects with multiple values?

In python, the curly brackets { } are used for dictionaries, which are similar to javascript objects (which sounds like what you're familiar with). The hard brackets [ ] are called lists. Your desired response looks like a dictionary with a key that has a dictionary as its value. Unfortunately, you can't add key-value pairs into a list or array in python, so you should instead make another dictionary instead of a list or rethink what your desired list would look like (perhaps only the values and not the keys).

TL;DR: you are appending dictionaries to your list:
.append({obj[0]: obj[1]})

{obj[0]: obj[1]} is a dictionary you are appending to the list.
In python you can have a list of dictionaries but you cant have just key-value pairs in a list

How to add multiple objects into a single array in a JSON file using Python?

You can use:

import json
from os import path

users = [
"username": "",
"phone": ""

username = input('Username: ')
phone = input('Phone: ')
for user in users:
user['username'] = username
user['phone'] = phone

my_path = 'users.json'
if path.exists(my_path):
with open(my_path , 'r') as file:
previous_json = json.load(file)
users = previous_json + users

with open(my_path , 'w') as file:
json.dump(users, file, indent=4)

In your code, you are just appending every entry to your file on each run of your code. To have only one list with all your entries, you have to first read the previous entries and then add the new entry.

Create JSON with multiple values

You need to check the size of the current object, and insert the data to the position of that size:

$(document).ready(function() {  var maj = {};
$("#btnSubmitRejetRefModele").click(function() { var size = Object.keys(maj).length; var data = { one: 'a' + (size+1), two: 'b' + (size+1), three: 'c' + (size+1) } maj[size] = data; console.clear(); console.log(maj); });});
<script src=""></script><button id="btnSubmitRejetRefModele">Add</button>

How do I make a JSON object with multiple arrays?

On the outermost level, a JSON object starts with a { and end with a }.

Sample data:

"cars": {
"Nissan": [
{"model":"Sentra", "doors":4},
{"model":"Maxima", "doors":4},
{"model":"Skyline", "doors":2}
"Ford": [
{"model":"Taurus", "doors":4},
{"model":"Escort", "doors":4}

If the JSON is assigned to a variable called data, then accessing it would be like the following:['Nissan'][0].model   // Sentra['Nissan'][1].model // Maxima['Nissan'][2].doors // 2

for (var make in {
for (var i = 0; i <[make].length; i++) {
var model =[make][i].model;
var doors =[make][i].doors;
alert(make + ', ' + model + ', ' + doors);

Another approach (using an associative array for car models rather than an indexed array):

"cars": {
"Nissan": {
"Sentra": {"doors":4, "transmission":"automatic"},
"Maxima": {"doors":4, "transmission":"automatic"}
"Ford": {
"Taurus": {"doors":4, "transmission":"automatic"},
"Escort": {"doors":4, "transmission":"automatic"}
}['Nissan']['Sentra'].doors // 4['Nissan']['Maxima'].doors // 4['Nissan']['Maxima'].transmission // automatic

for (var make in {
for (var model in[make]) {
var doors =[make][model].doors;
alert(make + ', ' + model + ', ' + doors);


Correction: A JSON object starts with { and ends with }, but it's also valid to have a JSON array (on the outermost level), that starts with [ and ends with ].

Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.


  • JSON specification
  • JSONLint - The JSON validator

Serialize and add multiple items to json

The error is because you're adding another JSON element to a non-valid JSON array. Your file's content must follow the schema:

[ { content }, { another content } ]

Just like any documentation out there will show.
What about serializing and deserializing the JSON from the TEXT dealing with a Json Array?

model.IDCliente = StartID;
var fileName = @"D:\AnagraficaClientiJsonMemory\clienti.txt";
var fileContent = File.ReadAllText(fileName);
var models = JsonConvert.DeserializeObject<List<ClienteModel>>(fileContent);
File.WriteAllText (fileName, JsonConvert.SerializeObject(models));
MessageBox.Show("Cliente aggiunto correttamente.");

This way, you could do any other processing with the models. An alternative is reading the File's content looking for the closing character of the JSON (']') and append your new JSON before.

Related Topics

Leave a reply