Reputation: 2462
Is there any way to convert some parts of JSON string to booleans ?
My JSON string example:
{
"file_id": {
"width": "560",
"height": "270",
"esc_button": "1",
"overlay_close": "1",
"overlay_opacity": "1"
}
}
If this was my personal project, I believe I would just convert the output of booleans into true/false
strings and not 1 and 0
, but since it isn't I wonder if there is a way to set what properties from JSON string are booleans. In this example booleans should be: esc_button, overlay_close
but not overlay_opacity
...
So since this is JavaScript project, I wonder what are my options and is there any easy way to do this ? There are more settings from this JSON string, I just posted part of it. Settings change depending on click event (different file_id === different settings)
EDIT:
Just figured I could use parseInt(settings[file_id].esc_button)
to get boolean, but do I really have to use that all the time ? There might be other ways that I am not aware of.
Upvotes: 0
Views: 286
Reputation: 187044
JSON is just a data format. And if the data you are consuming chose to pass the string "0"
, you will get the string "0"
, and not false
.
If "0"
isn't what you want in your program you need to process the data a bit.
// for example
var processData = function(jsonString) {
var data = JSON.parse(jsonString);
data.esc_button = (data.esc_button == "1");
return data;
};
JSON.parse()
itself doesn't provide a way to do this. It just decodes the data as it is in the source. If you need something different, you need to translate.
Ideally you should get your data source to give you this data in a better format. If it has real boolean literal values instead, you don't have to do any translation at all.
{
"file_id": {
"width": 560,
"height": 270,
"esc_button": true,
"overlay_close": false,
"overlay_opacity": 1
}
}
If your JSON looks like that, you just parse it and your done. By removing the quotes from width and height, those are now number values that require no translation to use in other math. And by reporting true
or false
for boolean values, those will get parsed as boolean literals, not strings. And it all just works.
This also resolves ambiguity. In your original JSON you had "1"
for true
and "1"
for the opacity
value, which I assume is expected to be a number form zero to one. Now you can look at the raw JSON data and see the difference.
Upvotes: 1
Reputation: 60067
JS is a dynamic language. You can do it yourself.
if (my_object[its_property]==="1")
my_object[its_property] = true
else
my_object[its_property] = false;
Or more tersely my_object=(my_object[its_property]==="1");
.
Upvotes: 1