Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将字符串转换为对象_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 如何将字符串转换为对象

Javascript 如何将字符串转换为对象,javascript,angular,typescript,Javascript,Angular,Typescript,上面的代码抛出以下错误 未捕获的SyntaxError:JSON中位置46处的意外标记p 您只需将10px括在引号10px中,并确保在不同的引号之间交替使用,以避免断开字符串: var s = "{ "background-color": "#4a90e2", "margin": 10px }"; JSON.parse(s); 目前,JSON语法和javascript语法都不正确 JSON应该有字符串键和字符串值。目前你的10px不是一个字符串。你需要把这个换成10px 此外,用于对象键/值的

上面的代码抛出以下错误

未捕获的SyntaxError:JSON中位置46处的意外标记p


您只需将10px括在引号10px中,并确保在不同的引号之间交替使用,以避免断开字符串:

var s = "{ "background-color": "#4a90e2", "margin": 10px }";
JSON.parse(s);

目前,JSON语法和javascript语法都不正确

JSON应该有字符串键和字符串值。目前你的10px不是一个字符串。你需要把这个换成10px

此外,用于对象键/值的字符串中的引号会破坏字符串本身。您可以使用反勾号、反斜杠或单引号来正确封装字符串,而不破坏字符串:

单引号:

反斜杠:

背景:

请参见下面的工作示例:

var s={\background color\:\4a90e2\,\margin\:\10px\};
console.logJSON.parses 您的输入字符串无效

你不可能在另一个里面

此外,10px是一个字符串,因此您需要将引号括起来

应该作出改变-

var s = `{ "background-color": "#4a90e2", "margin": "10px" }`;

你必须使用不同类型的引号!
这将起作用:“{背景色:4a90e2,边距:10px}”。

首先,10px不应该是字符串吗?请调整…

这是一个无效的JSON字符串,10px需要如下所示:10px,因此对于JSON.parse,您不能。字符串是无效字符串,你不能在margin:10px==>margin:10px中缺少一个引号。你的字符串不是一个有效的json,因为错误表明它需要放在10px左右。已经有很多答案说明了同样的问题,你有什么新的地方吗?我在弹出类似的答案之前回答了,可能是网络。
var s = '{ "background-color": "#4a90e2", "margin": "10px" }';
var s = "{\"background-color\": \"#4a90e2\", \"margin\": \"10px\"}";
var s = `{ "background-color": "#4a90e2", "margin": "10px" }`;
var s = '{ "background-color": "#4a90e2", "margin": "10px" }';
JSON.parse(s);