简体   繁体   中英

How to get Key and Value from JSON object in Javascript(Postman)

I have a JSON object like this, I wanna access the list array elements with key and value in postman.

{
    "data": {
        "total": 1,
        "list": [
            {
                "id": 53,
                "name": "Sonu",
                "mobileNo": "6543213456",
                "address": "Greeny Pathway",
                "city": "NewYork",
                "mode": "Weekly",
                "duration": "15",
                "qty": null

            }
        ]
    },
    "success": true,
    "message": ""
}

How to separate it as Key and Value in Javascript like,

Key:   id,name,mobileNo,address,city,..
Value: 53,Sonu,6543213456,Greeny Pathway,NewYork,....

First remove comma from line : "qty": null, otherwise it will cause error in json parsing.

 var resultJSON = `{ "data": { "total": 1, "list": [ { "id": 53, "name": "Sonu", "mobileNo": "6543213456", "address": "Greeny Pathway", "city": "NewYork", "mode": "Weekly", "duration": "15", "qty": null } ] }, "success": true, "message": "" }`; var result = $.parseJSON(resultJSON); var myList = result.data.list[0]; $.each(myList, function(k, v) { //display the key and value pair alert(k + ' is ' + v); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

you can use below codes:

const keys = Object.keys(jsonObject);
const values = Object.values(jsonObject);

But your JSON object is deep, you should flatten it and then use keys and values of Object to make them separate.

You can get using key and value separately in a array.

 var a = { "data": { "total": 1, "list": [ { "id": 53, "name": "Sonu", "mobileNo": "6543213456", "address": "Greeny Pathway", "city": "NewYork", "mode": "Weekly", "duration": "15", "qty": null, } ] }, "success": true, "message": "" } var keyval = Object.keys(a.data.list[0]) console.log(keyval) var values = Object.values(a.data.list[0]) console.log(values)

JSON objects are key value pair you cannot get the keys and values in object form as you desire but you can get both in form of arrays from this code

var key = []
var values = []
list.map(function(l){  keys = Object.getOwnPropertyNames(l); 
keys.map(function(key) {values.push(l[key]);})})

Finally this works for me!(In Postman Script)

var resdata = JSON.parse(responseBody);
console.log(resdata);

key = Object.keys(resdata.data.list[0]);
console.log(key);

value =Object.values(resdata.data.list[0]);
console.log(value);

var resdata = JSON.parse(responseBody); console.log(resdata);

sorry, what is for responseBody here working as?

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