Appending a key value pair to a json object

后端 未结 4 1971
挽巷
挽巷 2020-12-16 00:48

This is the json object I am working with

{
    \"name\": \"John Smith\",
    \"age\": 32,
    \"employed\": true,
    \"address\": {
              


        
相关标签:
4条回答
  • 2020-12-16 01:33

    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.

    0 讨论(0)
  • 2020-12-16 01:35
    const newTestJson = JSON.parse(JSON.stringify(testJson));
    newTestJson.collegeId = {"eventno": "6062","eventdesc": "abc"};
    testJson = newTestJson;
    
    0 讨论(0)
  • 2020-12-16 01:45

    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.

    0 讨论(0)
  • 2020-12-16 01:51

    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"};
    
    0 讨论(0)
提交回复
热议问题