Skip to content

Instantly share code, notes, and snippets.

@catichenor
Last active January 19, 2016 23:23
Show Gist options
  • Save catichenor/0524564b6ac2f9fc2f3d to your computer and use it in GitHub Desktop.
Save catichenor/0524564b6ac2f9fc2f3d to your computer and use it in GitHub Desktop.
Convert JavaScript object string to something that can be parsed by JSON
unquotedPropertyString = '{obj_One: "Hello", obj_Two: "World!"}'; //Mixing camelCase and snake_case. It's a test. Sue me.
// brokenParse = JSON.parse(unquotedPropertyString); //Error! Why is obj_One not quoted?!?!?!
quotedPropertyString = unquotedPropertyString.replace(/([A-Za-z0-9_]+):/g, '\"$1\":'); //Result: '{"obj_One": "Hello", "obj_Two": "World!"}'
// * The above won't work if you're not using alphanumeric characters or underscores for your object property names.
// ** The regex will also have some false positives if your property values have colons in them. You'll need to adjust the regex for your purposes.
// For me, I needed to process output from the Node.js "formidable" module, which prints each property line-by-line, so I used output.replace(/([\s|\{]) ([A-Za-z0-9_]+): \"/g, '$1 \"$2\": \"')
// I also needed to fix the single quotes around property value from the formidable output, but that doesn't apply to this example.
workingParse = JSON.parse(quotedPropertyString); //Yay! It works!* **
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment