JSON.parse在数组内的空间上失败

时间:2016-01-24 11:21:01

标签: javascript json parsing whitespace

我已在javascript中保存此字符串

~/.AndroidStudio*
~/.java/.userPrefs

在使用js_str= '{"id":"1","user_id":"1","cat_id":"1","name_bz":"Chitwan National Park","name_cf":"Gokarna","cf_lattitude":"27.525","cf_longitude":"87.56","boundry":"[[27.0656,85.255],[27.3564, 85.3564],[27.98998, 85.6898]]\n","area":"989.948","forest_conditon":"Poor","natural_regeneration":"High","grazing_pressure":"Medium","forest_type":"Natural","wild_species_list":"Tiger, Leopard, Rhino","others":null}'; 时,它会给出

js_arr=JSON.parse(js_str)

第207列是逗号SyntaxError: JSON.parse: bad control character in string literal at line 1 column 207 of the JSON data 之后的空格。这个地方的空白是错误的。我不能使用正则表达式来删除空格,因为它会替换所有空格。

2 个答案:

答案 0 :(得分:3)

在错误的地方有一个\ n或者应该被转义。尝试改变:

"boundry":"[[27.0656,85.255],[27.3564, 85.3564],[27.98998, 85.6898]]\n"

为:

"boundry":"[[27.0656,85.255],[27.3564, 85.3564],[27.98998, 85.6898]]"

或将其转义为:

"boundry":"[[27.0656,85.255],[27.3564, 85.3564],[27.98998, 85.6898]]\\n"

答案 1 :(得分:3)

只需在\控制角色之前添加\n,一切都会好的。 JSON解析器的工作原理如下。

js_str= '{"id":"1","user_id":"1","cat_id":"1","name_bz":"Chitwan National Park","name_cf":"Gokarna","cf_lattitude":"27.525","cf_longitude":"87.56","boundry":"[[27.0656,85.255],[27.3564, 85.3564],[27.98998, 85.6898]]\\n","area":"989.948","forest_conditon":"Poor","natural_regeneration":"High","grazing_pressure":"Medium","forest_type":"Natural","wild_species_list":"Tiger, Leopard, Rhino","others":null}';

JSON.parse(js_str)

在Mozilla Firefox中成功测试了代码。 enter image description here