admin管理员组

文章数量:1415654

I have a problem here and no idea how to solve it...

I have a json file like this:

{"data":[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]}

But I need this format:

[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]

In javascript/jQuery I make an ajax request and get the json back:

$.ajax({
  type : "POST",
  cache : "false", // DEBUG
  url : weburl,
  dataType : "json",
  contentType : "application/json; charset=utf-8",
  success : function(data) {
    // Strip data?
  }
  });

Does anyone know how to do this? Thanks!

I have a problem here and no idea how to solve it...

I have a json file like this:

{"data":[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]}

But I need this format:

[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]

In javascript/jQuery I make an ajax request and get the json back:

$.ajax({
  type : "POST",
  cache : "false", // DEBUG
  url : weburl,
  dataType : "json",
  contentType : "application/json; charset=utf-8",
  success : function(data) {
    // Strip data?
  }
  });

Does anyone know how to do this? Thanks!

Share Improve this question edited Nov 13, 2012 at 16:45 Nico asked Nov 13, 2012 at 14:38 NicoNico 1,0811 gold badge25 silver badges39 bronze badges 1
  • Easiest thing would be to parse the json to an object, then convert the object's "data" property back to json. – qxn Commented Nov 13, 2012 at 14:41
Add a ment  | 

5 Answers 5

Reset to default 3
success : function (data) {
    var array = data ? data.data : null;
    // now perform the required operations with array variable.
}

This will return just the array, not wrapped in a object.

$.ajax({
    type: "POST",
    cache: "false", // DEBUG
    url: weburl,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        var arrayYouWant = data.data; // http://thedailywtf./Articles/Data-Data-data-Data.aspx
    }
});

Why do you need to strip it, you just reference it

success : function(data) {
    var myArrayofObjects = data.data;
}

In order to really understand read about the Member operators in Javascript, particularly the dot notation. JSON is a subset of Javascript and the JSON object is a Javascript object in the end.

Not sure what you mean by archive. Do you mean simply access the array that is associated with the data property?

The array is associated to the 'data' property in your JSON string. I would maybe change the name of the data argument passed into the success function.

Try this:

$.ajax({
    type: "POST",
    cache: "false", // DEBUG
    url: weburl,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(resp) {
        var yourArray = resp.data; 
        console.log(yourArray);
    }
});

本文标签: javascripthowto cut json stringStack Overflow