javascript 将字符串转换为javascript字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31892971/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:31:41  来源:igfitidea点击:

converting string to javascript dictionary

javascriptjsondictionary

提问by Mubashir Kp

i have a string like this which is retirieved from database. i need to convert the string to javascript dictionary.

我有一个这样的字符串,它是从数据库中检索出来的。我需要将字符串转换为 javascript 字典。

"['content':{'type':'file','path':'callie/circle'},'video':{'videoId':'CvIr-2lMLsk','startSeconds': 15,'endSeconds': 30'}]".

how do i convert the above string to a javascript dictionary ? should i convert the string to json first or not.? when i try json.parse, an error as shown below is being displayed

如何将上述字符串转换为 javascript 字典?我应该先将字符串转换为 json 还是不。?当我尝试 json.parse 时,正在显示如下所示的错误

Uncaught SyntaxError: Unexpected token '
at Object.parse (native)
at <anonymous>:2:6
at Object.InjectedScript._evaluateOn (<anonymous>:905:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:838:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)

回答by Sanjaya Pandey

Please correct your JSON string,

请更正您的 JSON 字符串,

Valid json is:  {"content":{"path":"callie/circle","type":"file"},"video":{"videoId":"CvIr-2lMLs??k","endSeconds":"30","startSeconds":15}}

Then convert string to JSON as:

然后将字符串转换为 JSON 为:

var obj = JSON.parse(string);

What I tried:

我试过的:

var obj = JSON.parse('{"content":{"path":"callie/circle","type":"file"},"video":{"videoId":"CvIr-2lMLs??k","endSeconds":"30","startSeconds":15}}');
console.log(obj.content);
var obj2 = obj.content;
console.log(obj2.path);>>callie/circle