最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - howto cut json string? - Stack Overflow

programmeradmin0浏览0评论

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);
    }
});
发布评论

评论列表(0)

  1. 暂无评论