Last active
January 19, 2016 23:23
-
-
Save catichenor/0524564b6ac2f9fc2f3d to your computer and use it in GitHub Desktop.
Convert JavaScript object string to something that can be parsed by JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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