gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:34:27 26 4
gpt4 key购买 nike

我有这样一个字符串:

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 更新后,我将其发布到 url:

$.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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com