javascriptregexjsonnode.js

missing quotation marks on keys in JSON


I have a string containing malformed JSON which is being provided to me where the keys are missing the quotation marks. The structure of the JSON is out of my control, so I need to work with what I have. I have found the solution that the OP posts in Parsing malformed JSON in JavaScript works, however one of the values contains a URL that the RegEx matches and transforms it into another key like value, resulting in really broken JSON. Any ideas?

I have also looked at jsonrepair, but not having much success there.


Solution

  • This should do it. All you needed to do was identify when a colon was followed by a forward-slash (like in http://) instead of in isolation. Note that this will fail in the event that one of your JSON values has a colon in it, so it may need more improvement for your use case.

    .replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:([^\/])/g, '"$2":$4');