简体   繁体   中英

How can i remove particular data from JSON response

I am getting service response like this.

Temp([
  {
    XXX: "2",
    YYY: "3",
    ZZZ: "4"
  },
  {
    XXX: "5",
    YYY: "6",
    ZZZ: "7"
  },
  {
    XXX: "1",
    YYY: "2",
    ZZZ: "3"
  }
]);

i want to remove temp to this response msg in javascript , like below .

[
  {
    XXX: "2",
    YYY: "3",
    ZZZ: "4"
  },
  {
    XXX: "5",
    YYY: "6",
    ZZZ: "7"
  },
  {
    XXX: "1",
    YYY: "2",
    ZZZ: "3"
  }
]

Firstly I don't think that is a JSON response. The proper JSON response would be like this.

{
"temp": [
    {
        "XXX": "2",
        "YYY": "3",
        "ZZZ": "4"
    },
    {
        "XXX": "5",
        "YYY": "6",
        "ZZZ": "7"
    },
    {
        "XXX": "1",
        "YYY": "2",
        "ZZZ": "3"
    }
  ]
}

Then you can extract the array by using.

response["temp"]

Let's say that source from where you get your JSONP response is safe and it allways gives correct JSONP response.

Basicly it means you will get response like:

functionName(jsonString)

Like in your example:

Temp([{"XXX":"2","YYY":"3","ZZZ":"4"},{"XXX":"5","YYY":"6","ZZZ":"7"},{"XXX":"1","YYY":"2","ZZZ":"3"}])

Extract JSON - method 1

If you only need object from response function parameter, you could do something like this:

var jsonObject = null;
try
{
    var response = 'Temp([{"XXX":"2","YYY":"3","ZZZ":"4"},{"XXX":"5","YYY":"6","ZZZ":"7"},{"XXX":"1","YYY":"2","ZZZ":"3"}])';
    var temp = response.split('(');
    delete temp[0];
    temp = temp.join('(').split(')');
    delete temp[temp.length-1];
    temp = temp.join(')');
    temp = temp.substring(1, temp.length-1);
    jsonObject = JSON.parse(temp);
}
catch(ex)
{
}
console.log(jsonObject);

Extract JSON - method 2 useing this method actually allows to have multiple json objects as function parameters. Let's assume that you do not know what method name JSONP result is designed to call.

So we can do something like:

var response = 'Temp([{"XXX":"2","YYY":"3","ZZZ":"4"},{"XXX":"5","YYY":"6","ZZZ":"7"},{"XXX":"1","YYY":"2","ZZZ":"3"}])';
try{
    var fnName = response.split('(')[0];
    var fn = new Function(fnName, response);
    var jsonObject = null;
fn(function(json){
    jsonObject = json;
});
    console.log(jsonObject);
}
catch(ex){
    console.log(ex.message);
}

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