I am using stringify to post an object to php in php even integers are string how can i fix this?

StackOverflow https://stackoverflow.com/questions/20132493

  •  03-08-2022
  •  | 
  •  

Domanda

I am using stringify to post an object to php,

In php i use json_decode($object,true) to get the object back into a object for and not a string.

However the values stay strings even for integers.

My question is there a way to decode it to it's original form ?

ints to ints. string to stings ..

Thanks

È stato utile?

Soluzione

Not sure what you're getting at:

php > var_dump(json_decode(42)); // decoding a PHP int
int(42)
php > var_dump(json_decode('42')); // decoding a PHP string
int(42)
php > var_dump(json_decode('"42"')); // decoding a json string, containing a number
int(42)
php > var_dump(json_decode('foo')); // decoding invalid json
NULL
php > var_dump(json_decode('"foo"')); // decoding a valid string
string(3) "foo"
php > var_dump(json_decode('{"42":"foo"}')); // json object
object(stdClass)#1 (1) {
  ["42"]=>
  string(3) "foo"
}

Altri suggerimenti

It sounds like your JSON is wrong, and has the ints as strings in that.

php> $o = json_decode('{"test": 42}')
=> stdClass Object
(
    [test] => 42
)
php> is_int($o->test)
=> 1

If they're properly ints in the JSON, they're ints coming out of json_decode.

PHP will decode an integer as an integer if the value doesn't have quotes around it in the json string.

See here for an example: http://3v4l.org/ue67M

So you need to ensure that in the json you have "myint": 1 and not "myint": "1".

Which means the real issue here is the how you are creating the json in the first place.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top