Javascript 将字符串转换为 json 数组

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

convert string to json array

javascriptjson

提问by robert

I get this response from an Ajax request. Javascript seems to intepret it as a string. (When I say alert this.responseText, the whole string is shown)

我从 Ajax 请求中得到了这个响应。Javascript 似乎将其解释为字符串。(当我说 alert this.responseText 时,会显示整个字符串)

How can i convert it to a javascript object (JSON)?

如何将其转换为 javascript 对象 (JSON)?

{"response": {
   "success": "The activity has been removed",
   "message": "0"

  }
}

I am not using jquery.

我没有使用 jquery。

采纳答案by Pointy

It's not the safest thing in the world, but you can do this:

这不是世界上最安全的事情,但您可以这样做:

var value = null, txt = this.responseText;
eval("value = (" + txt + ")");

It might be a little safer to do:

这样做可能更安全一点:

var value = null, txt = this.responseText;
!function(window) { eval("value = (" + txt + ")"); }();

but there are still all sorts of potential hacks. You're better off using a library.

但仍然存在各种潜在的黑客攻击。你最好使用图书馆。

回答by knepe

If you use jQuery, JSON.parse(this.responseString);or jQuery.parseJSON(this.responseString);should work.

如果你使用jQuery,JSON.parse(this.responseString);还是jQuery.parseJSON(this.responseString);应该可以的。

回答by mway

Use the JSON library?

使用 JSON 库?

json.org

json.org

source

来源