Javascript 从json“未定义”中获取价值我有什么问题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33418720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get value from json "undefined" what I have wrong?
提问by Leonardo Cavani
I have this string:
我有这个字符串:
[
{"id":"001",
"name":"Charlie"},
{"id":"002",
"name":"Ellie"},
]
Them, I save this string in a variable and I parse it:
他们,我将此字符串保存在一个变量中并解析它:
function parseJSON(string){
var mylovelyJSON = JSON.stringify(string);
alert(mylovelyJSON[id]);
}
When I make my alert, I get and "undefined", I also tried with "mylovelyJSON.id", And I get the same.
当我发出警报时,我得到了“未定义”,我也尝试了“mylovelyJSON.id”,我得到了同样的结果。
Could not be a Json? I get this string from an php array.
不能是 Json 吗?我从一个 php 数组中得到这个字符串。
回答by Quentin
There are many things wrong here
这里有很多问题
Your JSON is invalid
您的 JSON 无效
You have an extra ,
just before the end of the array that you need to remove
,
在需要删除的数组末尾之前有一个额外的
You need to parse
你需要解析
JSON.stringify
converts a JavaScript data structure into a string of JSON.
JSON.stringify
将 JavaScript 数据结构转换为 JSON 字符串。
You need to go the other way and use JSON.parse
.
您需要走另一条路并使用JSON.parse
.
Square-bracket notation takes strings
方括号表示法接受字符串
mylovelyJSON[id]
takes the value of id
(which is undeclared so, in this case, would throw a reference error) and gets the property with the name that is the same as that value.
mylovelyJSON[id]
获取的值id
(未声明,因此在这种情况下会引发引用错误)并获取名称与该值相同的属性。
You need either mylovelyJSON["id"]
or mylovelyJSON.id
你需要mylovelyJSON["id"]
或者mylovelyJSON.id
You have an array
你有一个数组
Your JSON consists of an array of objects, not a single object.
您的 JSON 由一组对象组成,而不是单个对象。
You need to get an object out of the array before you can access properties on it.
您需要先从数组中取出一个对象,然后才能访问它的属性。
mylovelyJSON[0]["id"]
mylovelyJSON[0]["id"]
var json_text = '[{"id":"001","name":"Charlie"},{"id":"002","name":"Ellie"}]';
parseJSON(json_text);
function parseJSON(string){
var result_of_parsing_json = JSON.parse(string);
document.body.appendChild(
document.createTextNode(result_of_parsing_json[0]["id"])
);
}
回答by Get Off My Lawn
Two things are wrong here
这里有两件事是错误的
- Your array ends with a comma, which isn't valid json
- You are converting a string to javascript, and stringify does the opposite of that.
- 您的数组以逗号结尾,这不是有效的 json
- 您正在将字符串转换为 javascript,而 stringify 则与此相反。
So something like this might work:
所以这样的事情可能会奏效:
var id = 0;
function parseJSON(string){
var mylovelyJSON = JSON.parse(string);
alert(mylovelyJSON[id]);
}
NoteI am assuming that id
is a global variable...
注意我假设这id
是一个全局变量......