I have some objects that I'm parsing from json using native browser implementations. Some of the objects' properties are numbers. For the moment, the numbers are parse from json as strings and I use parseInt to cast the string to the int I need.
The problem is that I've got 23 objects I do this with and overall about 80 properties that I'm parsing to ints like this:
if (TheObject && TheObject.TheProperty) {
TheObject.TheProperty = parseInt(TheObject.TheProperty, 10);
}
There are many lines of code that look very similar. Is there a way using prototypes or something to change the way the JSON.parse function works so that each time the parser runs it checks to see if a string property is actually an int and if so cast it directly as such?
Thanks.
JSON is a JavaScript-based object/value encoding format that looks very close to raw JavaScript and can be very easily parsed by JavaScript code because JavaScript can effectively evaluate a JSON string and re-materialize an object from it.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
The integer type is used for integral numbers. JSON does not have distinct types for integers and floating-point values. Therefore, the presence or absence of a decimal point is not enough to distinguish between integers and non-integers. For example, 1 and 1.0 are two ways to represent the same value in JSON.
JSON.parse
accepts a second argument in the form of a function that can do some post processing.
JSON.parse('{"p": "5"}', function(k, v) {
return (typeof v === "object" || isNaN(v)) ? v : parseInt(v, 10);
});
I you don't want to process all numeric strings, then create a lookup table of the properties you do want.
var props = {"p":1, "some_prop":1, "another_prop":1};
JSON.parse('{"p": "5"}', function(k, v) {
return props.hasOwnProperty(k) ? parseInt(v, 10) : v;
});
JSON can handle numbers as follow:
{
"TheObject":{
"TheProperty":5
}
}
If your property was doublequoted then it's a string else it's a numeric, boolean (true
and false
values), null
or just something that cause parse error.
See http://json.org/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With