我有一个像这样的字符串:
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 的控制台中看到的内容:
它看起来像一个数组,但实际上只是另一个键为“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/