这是我的服务器端 PHP 脚本:
echo json_encode(
array(
"1" => "foo",
"2" => "bar"
)
);
索引是字符串。
我正在$.ajax()
使用 jQuery 获取这个数组,并使用 Chrome 的开发人员工具,我可以看到它将索引解释为数值而不是字符串。
将 JSON 从服务器传递到客户端时,如何保留该字符串类型?还是在将 JSON 数据从服务器传输到客户端时,类型的概念完全丢失了?
Strings can be numeric and strings, and even booleans, thanks to type coercion and duck typing (if it looks, walks, and quacks like a duck, it is a duck), since both are loosely typed languages. You should be just fine handling it like a string.
In the case of Chrome developer tools, you have a string that consists only of numeric characters. Therefore, it's also a numeric data type (it "looks like a duck").
Perhaps if you explain what, exactly, it is you're doing that isn't working, we could help you with a better way.
这是因为在 PHP 中,javaScript 调用的对象是 php 中的数组。在 JavaScript 中,数组索引不能是字符串,它们必须是正整数。
如果您希望 JavaScript 将其解释为数组,请给它一个 0 索引并使索引为整数而不是字符串。
您的代码已经完成了您希望它执行的操作。键是字符串。
var jsonStr = '{"1":"foo","2":"bar"}';
var obj = JSON.parse(jsonStr);
for (key in obj) {
console.log(typeof key, key); // string 1, string 2
}
编辑(根据评论)
永远不要依赖 JavaScript 对象的排序顺序,它可能因浏览器而异。