I have a PHP script that outputs JSON data which is parsed by Javascript in Browsers, and also by iPhone and Android apps.
Previously, I found that when PHP converted array data into a JSON, it would make all numberical values into strings as indicated by double quotes. So, for example, "id" : 1 would become "id" : "1". This seemed to confuse some of the Javascript functions that received the JSON data, so I ran this regular expression on the JSON in PHP in order to make sure numbers weren’t made into strings:
$JSONOutput = preg_replace('/"(-?\d+\.?\d*)"/', '$1', json_encode($JSONOutput));
However, this also has the effect of removing double quotes from both keys and values, so 1 : "first value" becomes "1" : "first value". It turns out this is a problem because if JSON keys aren’t strings, then the iPhone app that recieves the data complains.
So, what I want to do is make sure all values in the JSON are preserved as integers, but all keys are made into strings. Is there a way I can run the regular expression I have above on just the values? Or any other process that would give me a similar result?
You’re much better off avoiding post-processing the string.
The answer here is to make sure that the number values really are numbers. If you’re seeing strings with digits in them where you expect numbers, it’s because the value in the PHP object/array is not a number. That’s what you need to fix.
For example, this code:
…quite correctly produces this output:
Note how the value that’s really a number in the PHP code comes out as a number in the JSON.
So rather than post-processing the string, the answer is to correct the data you’re feeding into
json_encode.Replying to your comment below:
It doesn’t make the slightest difference. For example, this code:
produces this output:
Again note that the numbers are numbers in the input, and therefore numbers in the output.
Also note that PHP correctly handles it if the keys of the object are numbers:
produces