简体   繁体   English

将字符串解析为对象?(JavaScript)

[英]Parse a string into object?(JavaScript)

Would it be possible to parse a string as follows… {"Key": "Value"} back into a object?是否可以将字符串解析如下... {"Key": "Value"}回对象? When I ever I try to parse it, I receive errors.当我尝试解析它时,我收到错误。 I've been trying to use json.parse , but that does not work either.我一直在尝试使用json.parse ,但这也不起作用。

This is what i have mapped out, but for this format it fails.这是我已经绘制出来的,但是对于这种格式它失败了。

 // Creating a list of objects, while mapping properties of an object let obj = "{ "key": "3" }"; let objList = Object.entries(obj).map(([key, value]) => Object.fromEntries(new Map([ [key, value] ])));

let obj = "{
  "key": "3"
}";

This is incorrect: if you want to write a multiline string , you have to put a \\ at the end of the line:这是不正确的:如果你想写一个多行 string ,你必须在行尾放一个\\

let obj = "{\
    "key": "3"\
}";

But there is another error: you have to escape the " :但是还有另一个错误:您必须转义"

let obj ="{\
    \"key\": \"3\"\
}";

You could use ' for enclosing string instead of " so you don't need the escape:您可以使用'围住字符串,而不是"所以你不需要越狱:

let obj = '{\
    "key": "3"\
}';

Anyway this is a little string, you could write it in one line:无论如何,这是一个小字符串,您可以将其写在一行中:

let obj = '{"key": "3"}';

Now you can use JSON.parse.现在您可以使用 JSON.parse。

 let obj = '{"key": "3"}'; console.log( JSON.parse(obj) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM