Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a key value pair to a json object

Tags:

json

This is the json object I am working with

{
    "name": "John Smith",
    "age": 32,
    "employed": true,
    "address": {
        "street": "701 First Ave.",
        "city": "Sunnyvale, CA 95125",
        "country": "United States"
    },
    "children": [
        {
            "name": "Richard",
            "age": 7
        },
        {
            "name": "Susan",
            "age": 4
        },
        {
            "name": "James",
            "age": 3
        }
    ]
}

I want this as another key-value pair :

"collegeId": {
                      "eventno": "6062",
                      "eventdesc": "abc"
                                            }; 

I tried concat but that gave me the result with || symbol and I cdnt iterate. I used spilt but that removes only commas.

concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));

How do I add a key pair value to an existing json object ? I am working in javascript.

like image 853
Aayush Avatar asked Jan 11 '13 05:01

Aayush


3 Answers

This is the easiest way and it's working to me.

var testJson = {
        "name": "John Smith",
        "age": 32,
        "employed": true,
        "address": {
            "street": "701 First Ave.",
            "city": "Sunnyvale, CA 95125",
            "country": "United States"
        },
        "children": [
            {
                "name": "Richard",
                "age": 7
            },
            {
                "name": "Susan",
                "age": 4
            },
            {
                "name": "James",
                "age": 3
            }
        ]
    };
    testJson.collegeId = {"eventno": "6062","eventdesc": "abc"};
like image 53
Jobert Enamno Avatar answered Oct 25 '22 08:10

Jobert Enamno


Just convert the JSON string to an object using JSON.parse() and then add the property. If you need it back into a string, do JSON.stringify().

BTW, there's no such thing as a JSON object. There are objects, and there are JSON strings that represent those objects.

like image 33
Jonathan M Avatar answered Oct 25 '22 08:10

Jonathan M


You need to make an object at reference "collegeId", and then for that object, make two more key value pairs there like this:

var concattedjson = JSON.parse(json1);
concattedjson["collegeId"] = {};
concattedjson["collegeId"]["eventno"] = "6062";
concattedjson["collegeId"]["eventdesc"] = "abc";

Assuming that concattedjson is your json object. If you only have a string representation you will need to parse it first before you extend it.

Edit

demo for those who think this will not work.

like image 27
Travis J Avatar answered Oct 25 '22 07:10

Travis J