Remove String from JSON

痴心易碎 提交于 2020-01-25 18:12:47

问题


I want to feed a dijit.form.Select (Dojo Select-Box) with a Data-Store (JsonRest). The Problem is, that the JSON-Parser only accepts JSON in this format:

[
  {id:"1", name:"One1"},
  {id:"2", name:"Two1"}
];

The REST-API of the webapplication we want to call delivers the following JSON:

{
  "data": [
      {id:"1", name:"One1"},
      {id:"2", name:"Two1"}
],
    "total": 2,
    "start": 0,
    "sort": "name",
    "order": "asc",
     "size": 2
};

That is why the Select Box does not show any data. Therefore, we need to remove the {"data": part and the last part of the JSON message bevore passing it to the Dojo Select Box.

The Data is stored in a JsonRest Object. So the question is how we can remove the first and the last part of the JSON in a way that simply this here is given to the Select-Box:

[
  {id:"1", name:"One1"},
  {id:"2", name:"Two1"}
];

Thank you for your answers and best regards Ben


回答1:


Create a new Array variable from the data for the dojo select seems simplest ...

var restapidataObj = {
  "data": [
      {id:"1", name:"One1"},
      {id:"2", name:"Two1"}
    ],
    "total": 2,
    "start": 0,
    "sort": "name",
    "order": "asc",
     "size": 2
};

var dojoSelectArray = restapidataObj.data;

Now pass dojoSelectArray to dojo




回答2:


Store the result in a object and access the data property of that object.

var result = {
  "data": [
  {id:"1", name:"One1"},
  {id:"2", name:"Two1"}
],
   "total": 2,
   "start": 0,
   "sort": "name",
   "order": "asc",
   "size": 2
};

result.data would give you the data array.

Check the javascript object documentation at MDN




回答3:


resultFromServer =

     {
       "data": [
           {id:"1", name:"One1"},
           {id:"2", name:"Two1"}
     ],
         "total": 2,
         "start": 0,
         "sort": "name",
         "order": "asc",
          "size": 2
     };

this convert to object (Use this incase resultFromServer is a string)

    var Output = eval('('+ resultFromServer+')')

this gives your output

    JSON.stringify(Output.data)

gives the string

    "[{"id":"1","name":"One1"},{"id":"2","name":"Two1"}]"


来源:https://stackoverflow.com/questions/22377359/remove-string-from-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!