4

I am using json_encode to transform my php multidimensional array to output json. Normally, this function would convert all values to strings. To make sure that integers values are send to javascript as integer values, I am using the numeric check:

$json = json_encode($data, JSON_NUMERIC_CHECK);

This works fine in all but one case for my app. In the php array (which is extracted from the database), there is one field that contains very large integers. I save it to database as a VARCHAR, but unfortunately this is converted to an integer when encoding to json. The problem is that since this is a very large integer, it gets rounded and therefore does not represent the true value. How could I tackle this problem?

Adam
  • 35,919
  • 9
  • 100
  • 137
Bjorn
  • 904
  • 10
  • 29
  • 3
    PHP 5.4 has `JSON_BIGINT_AS_STRING`, which probably does what you want. – Francis Avila Dec 19 '12 at 17:35
  • Thanks for the suggestion, it looks like it would solve the problem for v5.4. However, I am using v5.3, so I'm hoping to find a solution for this version. – Bjorn Dec 20 '12 at 09:27
  • It seems that constant only works for the json_decode function – Bjorn Jan 09 '13 at 13:51
  • maybe interesting? [Handling big user IDs returned by FQL in PHP](http://stackoverflow.com/questions/2907806/handling-big-user-ids-returned-by-fql-in-php) – Ryan Vincent Dec 13 '15 at 15:03

2 Answers2

0

Do you want the large number to be transformed to an integer? Your question leads me to believe you don't. If that's the case, remove the JSON_NUMERIC_CHECK option from the call and it shouldn't change the encoding of the field.

Documentation about this (and other) constants is here.

Thomas
  • 1,402
  • 1
  • 11
  • 14
  • Thanks for your answer. Your solution would actually solve the problem, but then I would have to manually convert all other values to integers. I was looking for a solution that would avoid that. – Bjorn Dec 19 '12 at 17:33
  • What version of PHP are you using? – Thomas Dec 19 '12 at 18:02
  • Then it sounds like you are running into a problem similar to http://stackoverflow.com/questions/211345/working-with-large-numbers-in-php. Granted, this question is about big ints in math functions. However, some of the suggestions here could easily be translated to address your problem. – Thomas Dec 20 '12 at 14:30
0

Maybe is to late but i did hit the same problem, and stuck on PHP 5.3 on the server because of legacy code that must be run with that version. The solution that i used is dumb, but did work for me: simple add an space character at the end of the long integer that is varchar readed from the db, and before sending it to json encode with JSON_NUMERIC_CHECK.

cybercow
  • 427
  • 1
  • 4
  • 18