简体   繁体   中英

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 . 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. The lambda function takes the ajax request and inserts their survey into a MongoDB instance using mongoose.

When the string comes into the lambda function, it looks like this:

"{ 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. 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?

Thanks!

JSON strings need their string properties and values to be double-quoted. Use a regular expression and 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. Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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