3

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.

Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • This question is different from the linked question because it doesn't consider `json_encode()` turning strings back into numbers, see https://3v4l.org/YZS0F – Daniel W. Apr 09 '21 at 11:18
  • @mickmackusa yea but I don't need a solution anymore as I don't work with people anymore who don't accept standards. Look at this RFC that deals with the situation in question: https://wiki.php.net/rfc/json_numeric_as_string – Daniel W. Apr 09 '21 at 11:30
  • 2
    You ran a bad test and unjustly unhammered the dupe. https://3v4l.org/S8nXc `array_map()` does not modify by reference. – mickmackusa Apr 09 '21 at 11:30
  • @mickmackusa kudos! thanks for guiding me to my mistake! – Daniel W. Apr 09 '21 at 11:34

2 Answers2

3

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))

nl-x
  • 11,762
  • 7
  • 33
  • 61
  • `stringify` is not a valid PHP function, is it? I get your concept tho, helpful to me. I was hoping for a simple bitflag that always adds quotes :( – Daniel W. Jun 23 '14 at 12:06
  • @DanFromGermany stringify was a typo. It's fixed. It was meant to be recursive – nl-x Jun 23 '14 at 12:07
  • There is a native function to recursively iterate all leafnodes: `array_walk_recursive()`. [Demo](https://stackoverflow.com/a/67023516/2943403) – mickmackusa Apr 09 '21 at 15:23
1

If you're building your json data from a one-dimensional array, you can use

echo json_encode(array_map('strval', $data));

This technique will unconditionally convert all values to strings (including objects, nulls, booleans, etc.).

If your data might be multidimensional, then you'll need to call it recursively.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Miraage
  • 3,334
  • 3
  • 26
  • 43