javascript - 使用 jQuery 解析 JSON 将数组转换为哈希

标签 javascript jquery arrays json

我有一个像这样的字符串:

string = '{ "key": [
  { "foo": "bar" }
] }';

通过执行此操作将字符串转换为 JSON 对象

json = $.parseJSON(string);

然后它看起来像这样:

{ "key":
  { "0":
    { "foo": "bar" }
  }
}

所以看起来数组已转换为哈希值。

期望的结果是:

{ "key": [
  { "foo": "bar" }
] }

实现这一目标的最佳方法是什么?背景:我将 JSON 数据发布到 URL,但需要数组保持完整,以便收件人可以相应地解析它。

更新

这是我在 Chrome 37.0.2062.120 和 jQuery 1.11.1 的控制台中看到的内容:

enter image description here

它看起来像一个数组,但实际上只是另一个键为“0”的哈希值。还是我弄错了什么?

更新2

将字符串转换为 JSON 更新后,我将其发布到网址:

$.ajax({
    url: 'http://test.com',
    data: json,
    dataType: 'jsonp',
    type: 'post'
  })

到达地点

{ "key":
  { "0":
    { "foo": "bar" }
  }
}

最佳答案

发送 AJAX 时,您可以自己对 JSON 进行编码

对于 JSONP,使用

var json = '{ "key": [  { "foo": "bar" }] }';
var jsObj = $.parseJSON(json);
$.ajax({
    url: 'http://test.com',
    // You have to convert your JS object into a JSON string on your own
    // jQuery will convert them into form encoded values if you leave it as an object
    // But you want to send your whole JSON as one of the keys, 
    // so do use an object around your json to specify the the name of the
    // key value pair containing the JSON
    data: {myKey: JSON.stringify(jsObj)},
    dataType: 'jsonp',
    // The answer at http://stackoverflow.com/questions/6410810/rails-not-decoding-json-from-jquery-correctly-array-becoming-a-hash-with-intege
   // suggests you may need this for Rails to understand it
    contentType: 'application/json'
    // type can't be post for JSONP
    // type: 'post'
  })

对于 POST,请使用

$.ajax({
    url: '/my/url/',
    // For POST, you can post the entire string, converting it on your own
    data: JSON.stringify(jsObj),
    type: 'POST'
  })

关于javascript - 使用 jQuery 解析 JSON 将数组转换为哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25856959/

相关文章:

javascript - 单击时从 li 中删除类属性

javascript - 选择-选择多选 - 根据第一个的 selected.count 禁用第二个选择

python - 带有权重的 numpy 数组部分和

arrays - 删除具有相同第一列和最小第二列的行

javascript - 将数据存储到 javascript 变量中

java - GWT:如何将 java 数组传递给 javascript native 方法?

Javascript 图表库

javascript - 使用 Promises 处理分支

javascript - bootstrap jQuery 验证插件..错误放置问题

在函数内的堆栈上创建一个结构体,并将其分配给在另一个函数中创建的数组的数组位置