Check If A Json Value Match A Number With Leading Zero And Convert It To A String
Solution 1:
Ideally, if you could cause phpMyAdmin to emit valid JSON, that would be the best choice.
However, you could do some reasonable custom fixups using regular expressions. For example, the example you gave:
// data is from the file // match on "code":0####var fixCode = /"code":(0[0-9]+),/g;
var results = JSON.parse(
data.replace(fixCode, function(match, code) {
// rebuild the "code" property with quotes // (or convert to a VALID number):return'"code": "' + code + '", ';
}));
Results:
[ { id:1,
country:0,
code:'056897',
customer:'Joe Harris' },
{ id:2,
country:2,
code:'054597',
customer:'Frank Foe' } ]
Solution 2:
JSON doesn't allow leading zeros in number see rfc4267 section 2.4. That is, if you have a number with leading zero, it's not proper JSON.
If you really need to parse this file, you can prepend it with something like exports =
, but there is no guarantee that this will work as expected, since javascript may treat leading zero as a sign of octal number, if no digits more than 7 are used: e.g. 017 === 15
, but 018 === 18
Solution 3:
I know it may seem weird but the quickest solution I often use to convert a number to a string is, str = num+''
.
Here some other cases and perfs http://jsperf.com/scunliffe-number-to-string
Solution 4:
I don't know whether this will help you, but for converting the string containing an integer with leading zeros, you can use this:
var x = parseInt("00001000",10);
...which will correctly put 1000 as an integer value into x.
Post a Comment for "Check If A Json Value Match A Number With Leading Zero And Convert It To A String"