简体   繁体   中英

Javascript - fix a malformed JSON

I'm receiving a JSON from a source I have no control over. Some of the fields in the JSON look like this:

"itemName":"lorem ipsum "dolor" sit amet"

or:

"itemName":"lorem ipsum "dolor", sit amet"

This fails when I try to parse it... The JSON is pretty long, too. I have an idea of how to fix this (going over the quotes and checking the characters before and after), but it's quite a large task for just parsing a JSON... I was wondering if anyone knows of an easy way to do this, or if there's a library which already takes care of it...

You can use regex to basically parse around the quotes. Depending on how complicated the JSON is, you could set it up. Here's a basic version of just fixing up one line. As others have suggested, you're better off getting this fixed at the source.

var str = '"itemName":"lorem ipsum "dolor", sit amet"';
tryParse(str);
// first capture (p1) grabs the key, (p2) grabs the val
str.replace(/(".*:"?")(.*)"/gi, function(match, p1, p2) {
  str = p1 + p2.replace(/"/g, '\\"') + '"';
});
tryParse(str);

function tryParse(str) {
  str = '{' + str + '}';
  try {
    console.log(JSON.parse(str));
  } catch (e) {
    console.error(e);
  }
}

Results

[SyntaxError: Unexpected token d]
{ itemName: 'lorem ipsum "dolor", sit amet' }

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