1

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!

Kyle Frye
  • 111
  • 1
  • 11

2 Answers2

3

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • This worked! Thanks so much. I should've posted this hours ago. I'll accept the answer in two minutes when I can. Cheers! – Kyle Frye Jul 19 '18 at 01:51
  • @KyleFrye The above regex is fragile and will corrupt data if your JSON contains any values with single quotes in them, even if they are escaped, e.g. `{title: 'John\'s Awesome Survey'}` will become `{"title": "John"s Awesome Survey"}` which is invalid JSON and will error out if you try to parse it with JSON.parse(). Also, it will corrupt any value with a word followed by a colon, e.g. `{title: 'Puppies: Do you love them!?'}` will become `{"title": ""Puppies": Do you love them!?"}` which is also invalid and will also fail JSON.parse(). My answer handles those scenarios. – pretzelhammer Jul 19 '18 at 02:12
0

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
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98