Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbers in quotes using json_encode() [duplicate]

Tags:

json

php

Various 3rd party companies are forcing us to use non-conventional code and produce non-standard output.

We are using standard json_encode() to output a JSON variable in JS/HTML which looks like:

"custom":{"1":2,"2":7,"3":5}

Now they tell us this isn't working for them, they need it this way:

"custom":{"1":"2","2":"7","3":"5"}

Can I force PHP to wrap quotes arround numbers? Maybe using cast (string) when we build the object before encoding?

Mainly, we need an opposite of the following option bitflag:

JSON_NUMERIC_CHECK (integer)

Encodes numeric strings as numbers. Available since PHP 5.3.3.

But I doubt this exists.

like image 290
Daniel W. Avatar asked Oct 21 '25 13:10

Daniel W.


1 Answers

Guess you need to fix this yourself. I can't think of a built-in function, but you can write your own:

function stringify_numbers($obj) {
    foreach($obj as &$item)
        if(is_object($item) || is_array($item))
            $item = stringify_numbers($item); // recurse!
        if(is_numeric($item)
            $item = (string)$item;
    return $obj;
}

Now you can use json_encode(stringify_numbers($yourObject))

like image 63
nl-x Avatar answered Oct 23 '25 04:10

nl-x



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!