Quoted numbers using json_encode ()

Various third-party companies force us to use non-standard code and produce non-standard output.

We use standard json_encode() to output the JSON variable in JS / HTML, which looks like this:

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

Now they tell us that this does not work for them, they need it like this:

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

Can I get PHP to wrap quotes around arround numbers? Maybe using cast (string) when we create an object before encoding?

Basically, we need the opposite of the following bitflag parameter:

JSON_NUMERIC_CHECK (integer)

 Encodes numeric strings as numbers. Available since PHP 5.3.3. 

But I doubt that it exists.

+2
json php
source share
3 answers

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

+3
source share

If you are creating data from an array, you can use

 array_map('strval', $data); 

// upd

You should probably call it recursive.

+2
source share

Using properties (string) seems to work.

 $custom = array( '1' => (string)$property, // ... ); 
+2
source share

All Articles