Javascript 从响应中获取 json 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5625149/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:07:46  来源:igfitidea点击:

Get json value from response

javascriptjson

提问by slandau

{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}

If I alert the response data I see the above, how do I access the idvalue?

如果我提醒响应数据,我看到了上述内容,我该如何访问该id值?

My controller returns like this:

我的控制器返回如下:

return Json(
    new {
        id = indicationBase.ID
    }
);

In my ajax success I have this:

在我的 ajax 成功中,我有这个:

success: function(data) {
    var id = data.id.toString();
}

It says data.idis undefined.

它说data.idundefined

回答by James Kyburz

If response is in json and not a string then

如果响应在 json 而不是字符串中,则

alert(response.id);
or
alert(response['id']);

otherwise

除此以外

var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301

回答by p.campbell

Normally you could access it by its property name:

通常你可以通过它的属性名称访问它:

var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);

or perhaps you've got a JSON string that needs to be turned into an object:

或者您可能有一个需要转换为对象的 JSON 字符串:

var foo = jQuery.parseJSON(data);
alert(foo.id);

http://api.jquery.com/jQuery.parseJSON/

http://api.jquery.com/jQuery.parseJSON/

回答by amit_g

Use safely-turning-a-json-string-into-an-object

使用安全地将 json-string-into-an-object

var jsonString = '{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

var jsonObject = (new Function("return " + jsonString))();

alert(jsonObject.id);

回答by Mike Lewis

var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301

resultsis now an object.

results现在是一个对象。

回答by arun

If the response is in json then it would be like:

如果响应在 json 中,那么它将类似于:

alert(response.id);

Otherwise

除此以外

var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';