Adding a new key value to json

A common task!

To add a new key-value pair to a JSON object, you can use the following methods:

Method 1: Using the json() function (JavaScript)

const jsonObject = JSON.parse('{"name": "John", "age": 30}');
jsonObject.newKey = "newValue";
console.log(jsonObject); // Output: {"name": "John", "age": 30, "newKey": "newValue"}

Method 2: Using the Object.assign() method (JavaScript)

const jsonObject = {"name": "John", "age": 30};
Object.assign(jsonObject, {"newKey": "newValue"});
console.log(jsonObject); // Output: {"name": "John", "age": 30, "newKey": "newValue"}

Method 3: Using the $.extend() method (jQuery)

const jsonObject = {"name": "John", "age": 30};
$.extend(jsonObject, {"newKey": "newValue"});
console.log(jsonObject); // Output: {"name": "John", "age": 30, "newKey": "newValue"}

Method 4: Using the dict.update() method (Python)

import json
json_object = json.loads('{"name": "John", "age": 30}')
json_object.update({"newKey": "newValue"})
print(json_object)  # Output: {'name': 'John', 'age': 30, 'newKey': 'newValue'}

Method 5: Using the Map class (Java)

import java.util.HashMap;
import java.util.Map;

Map<String, Object> jsonObject = new HashMap<>();
jsonObject.put("name", "John");
jsonObject.put("age", 30);
jsonObject.put("newKey", "newValue");
System.out.println(jsonObject);  // Output: {name=John, age=30, newKey=newValue}

These are just a few examples of how you can add a new key-value pair to a JSON object. The specific method you use will depend on the programming language and library you are using.