简体   繁体   English

如何将字符串化的Surveyjs类JSON对象转换为实际的JSON

[英]How to convert stringified surveyjs JSON-like object into actual JSON

I'm working on a an application that uses the survey building library surveyjs . 我正在开发一个使用调查构建库surveyjs的应用程序。 I'm building a tool where users can input a survey JSON from that website into a form that is then sent as a string via an ajax request that triggers an AWS Lambda function. 我正在构建一个工具,用户可以在该工具中将来自该网站的调查JSON输入表单,然后通过触发AWS Lambda函数的ajax请求以字符串形式发送。 The lambda function takes the ajax request and inserts their survey into a MongoDB instance using mongoose. lambda函数接受ajax请求,并使用mongoose将其调查插入MongoDB实例中。

When the string comes into the lambda function, it looks like this: 当字符串进入lambda函数时,它看起来像这样:

"{ pages: [ { name: 'page1', elements: [ { type: 'radiogroup', name: 'question1', title: 'IS THIS A SURVEY?', choices: [ { value: 'item1', text: 'Yes' }, { value: 'item2', text: 'No' } ] } ] } ]}"

And when I try to parse that string, I get this error: 当我尝试解析该字符串时,出现以下错误:

Error: JSON Parse error: Expected '}'

I think it might have something to do with the JSON keys not being strings. 我认为这可能与JSON键不是字符串有关。 I've also read that my use of single quotes could potentially be the problem, but I've exhausted my knowledge base. 我还读到我使用单引号可能是问题所在,但是我已经用尽了我的知识库。

Overall, my question is: How can I convert that string into a JSON object? 总体而言,我的问题是:如何将字符串转换为JSON对象?

Thanks! 谢谢!

JSON strings need their string properties and values to be double-quoted. JSON字符串需要将其字符串属性和值用双引号引起来。 Use a regular expression and replace : 使用正则表达式并replace

 const originalStr = "{ pages: [ { name: 'page1', elements: [ { type: 'radiogroup', name: 'question1', title: 'IS THIS A SURVEY?', choices: [ { value: 'item1', text: 'Yes' }, { value: 'item2', text: 'No' } ] } ] } ]}"; const finalStr = originalStr .replace(/'/g, '"') .replace(/(\\w+):/g, '"$1":'); console.log(JSON.parse(finalStr).pages); 

That said, it would be better to fix whatever's serving the results in the first place, if at all possible. 也就是说,如果可能的话, 最好首先修复所有可提供结果的内容。

If your lambda function is written using javascript then you can make use of eval to parse malformed JSON, however the eval 'd string is evaluated as actual javascript within the current context so to get the result you have to set a variable within the string. 如果您的lambda函数是使用JavaScript编写的,则可以使用eval解析格式错误的JSON,但是eval字符串在当前上下文中被评估为实际的javascript,因此要获得结果,您必须在字符串中设置一个变量。 Example: 例:

var malformedJsonString = "{unquotedName: 'single quoted value'}";
eval("var myParsedJsonObject = "+malformedJsonString+";");
// myParsedJsonObject now contains your parsed JSON object

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

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