简体   繁体   中英

Push string to JSON using JavaScript

I have a json of the below format

{
    "name": "Stub",
    "request": {
        "method": "GET",
        "url": "/thing/1/4"
    },
    "response": {
        "status": 200
    }
}

I would like to add the below part to my json

"queryParameters": {
            "Accept": {
                "equalTo": "xml"
            }
        }

so my final outcome is of the below format

{
    "name": "Stub",
    "request": {
        "method": "GET",
        "url": "/thing/1/4",
        "queryParameters": {
            "Accept": {
                "equalTo": "xml"
            }
        }
    },
    "response": {
        "status": 200
    }
}

I tried the below but it doesn't seem to help, I also tried to parse which didn't help either

obj['theTeam'].push("queryParameters": { "Accept": { "equalTo": "xml" } });
jsonStr = JSON.stringify(obj);

尝试

obj["request"]["queryParameters"] = { "Accept": { "equalTo": "xml" } }

I sugget to use your json like a object to access to the attributes into it:

// Try edit msg
var obj = {
    "name": "Stub",
    "request": {
        "method": "GET",
        "url": "/thing/1/4"
    },
    "response": {
        "status": 200
    }
};
var partToAdd = {
            "Accept": {
                "equalTo": "xml"
            }
};
obj.request.queryParameters = partToAdd;
console.log(obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM