简体   繁体   中英

JSON.parse - How to handle capitalized Boolean values?

I am working on a Node.js application that needs to handle JSON strings and work with the objects.

Mostly all is well and JSON.parse(myString) is all I need.

The application also gets data from third parties. One of which seems to be developed with Python. My application repeatable chokes on boolean values since they come captialized.

Example:

var jsonStr = "{'external_id': 123, 'description': 'Run #2944', 'test_ok': False}";

try{
   var jsonObj = JSON.parse(jsonStr);
}catch(err){
   console.err('Whoops! Could not parse, error: ' + err.message);
}

Notice the test_ok parameter - it all is good when it follows the Javascript way of having a lower case false boolean instead. But the capitalized boolean does not work out.

Of course I could try and replace capitalized boolean values via a string replace, but I am afraid to alter things that should not get altered.

Is there an alternative to JSON.parse that is a little more forgiving?

I don't mean to be rude but according to json.org , its an invalid json. That means you'll have to run a hack where you have to identify stringified boolean "True" and convert it to "true" without affecting a string that lets say is "True dat!"

First of all, I would not recommend using the code below. This is just to demonstrate how to convert your input string into a valid JSON. There were problems, one is the Boolean False , and another is the single quotes around property names. I'm not positive but I believe those need to be double quotes.

I don't believe having to convert a string into a valid JSON is a good choice. If you have no alternative, meaning you don't have access to the code generating this string, then the code below is still not a good choice because it will have issues if you have embedded quotes in the string values. ie you would need different string replace logic.

Keep all this in mind before using the code.

 var jsonStr = "{'external_id': 123, 'description': 'Run #2944', 'test_ok': False}"; try { jsonStr = jsonStr.replace(/:[ ]*False/,':false' ).replace( /'/g,'"'); var jsonObj = JSON.parse(jsonStr); console.log( jsonObj ); } catch (err) { console.err('Whoops! Could not parse, error: ' + err.message); } 

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