如何将带有双引号反斜杠的JSON字符串转换为Javascript对象
I get response json string from server like this:
我从服务器得到响应json字符串,如下所示:
$scope.text = '{"response":"{\"firstName\":\"John\",\"age\":454 }"}';
How to use $scope.text
in angular template page like this:
如何在角度模板页面中使用$ scope.text,如下所示:
{{text.response.age}}
This is my demo Demo
这是我的演示演示
1 个解决方案
#1
2
$scope.text = '{"response":"{\"firstName\":\"John\",\"age\":454 }"}';
The problem here is that this isn't JSON.
这里的问题是这不是JSON。
By itself:
通过它自己:
{"response":"{\"firstName\":\"John\",\"age\":454 }"}
… is JSON.
......是JSON。
However, once you wrap it in a JavaScript string literal, the \
is used as an escape character for the JavaScript string literal and gets consumed before it can appear in the JSON.
但是,一旦将其包装在JavaScript字符串文字中,\就会用作JavaScript字符串文字的转义字符,并在它出现在JSON中之前被消耗掉。
When you generate JSON embedded in JS, you need to escape the characters with special meaning in JS:
当您生成嵌入在JS中的JSON时,您需要在JS中转义具有特殊含义的字符:
$scope.text = '{"response":"{\\"firstName\\":\\"John\\",\\"age\\":454 }\"}';
It would also be a good idea to redesign your data structure so that your JSON doesn't contain strings of JSON in the first place:
重新设计数据结构也是一个好主意,这样你的JSON首先不包含JSON字符串:
$scope.text = '{"response": {"firstName":"John","age":454}}';
更多相关文章
- javascript适合移动端的响应式瀑布流插件实例演示
- Javascript正则表达式应该允许空和非空字符串,但它不会
- 获取拆分字符串数组的最后一个元素
- “错误:路径必须是字符串”(v5.10.0)
- javascript 截取字符串方法汇总
- JavaScript String(字符串对象)
- JS将字符串转换为数组
- 在变量名是字符串时声明变量?
- 可编辑div中的文本计数和子字符串