PHP Returning Numeric Values in JSON

When I wrote about launching a prototype of a new joind.in API, quite a few people started to try it out. My friend David Soria Parra emailed me to point out that many of the numbers in the API were being returned as strings. He said:


It‘s just a standard problem of PHP REST services. When I try to access it with java I have to convert it over and over again to ints.


I did have a quick look at the PHP manual page for json_encode but I didn‘t see anything mentioning this. A few weeks later (my inbox is a black hole and it takes a while to process these things) I fell over a throwaway comment to an undocumented constant JSON_NUMERIC_CHECK, and I added the constant name to my todo list. In the time it took for me to actually get around to googling for this, some wonderful person updated the PHP manual page (this is why I love PHP) to include it as a documented option, and someone else had added a user contributed note about using it.


It turns out, this constant does exactly what I need. Here‘s a simple use case:

echo json_encode(array(‘event_id‘ => ‘603‘));
echo json_encode(array(‘event_id‘ => ‘603‘), JSON_NUMERIC_CHECK);

and the output:

{"event_id":"603"}
{"event_id":603}


There are probably some situations in which you don‘t want all your looks-like-a-number data to be returned as a number, but for now it seems to be a good fit for api.joind.in.


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。