javascript 拆分和 JSON.parse
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5496020/
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
javascript split and JSON.parse
提问by gautamlakum
I want to parse array in JSON format using javascript. I have written following code.
我想使用 javascript 解析 JSON 格式的数组。我写了以下代码。
var data = "abc, xyz, pqr";
var data_array = data.split(',');
var data_parsed = JSON.parse(data_array);
alert(data_parsed);
It gives me the error of JSON.parse I have no idea how to resolve this javascript error.
它给了我 JSON.parse 的错误我不知道如何解决这个 javascript 错误。
回答by Darin Dimitrov
You don't have any JSON, so don't use JSON.parse. Once you split you already have an array whose elements could be used directly:
你没有任何 JSON,所以不要使用 JSON.parse。拆分后,您已经拥有一个可以直接使用其元素的数组:
var data = "abc, xyz, pqr";
var data_array = data.split(',');
alert(data_array[0]);
and if you want to convert this array to a JSON string you could do this:
如果您想将此数组转换为 JSON 字符串,您可以这样做:
var json = JSON.stringify(data_array);
alert(json);
回答by mattsven
That's because "abc, xyz, pqr"
isn't valid JSON. Plus, JSON.parse()
is meant to parse JSON strings, not arrays. What are you trying to do, perhaps we can better assist.
那是因为"abc, xyz, pqr"
不是有效的 JSON。另外,JSON.parse()
旨在解析 JSON 字符串,而不是数组。你想做什么,也许我们可以更好地提供帮助。
回答by user945389
This is actually a convenient short cut to json processing if you only need a smaller set of variables.
如果您只需要较小的变量集,这实际上是 json 处理的便捷捷径。
PHP:
PHP:
return $var1 .','. $var2 .',some_string_value.';
Javascript:
Javascript:
var myReturnArray = returnValue.split(',');