encode to create strings

I have to json_encode a PHP array to a JavaScript array. Unfortunately the jQuery library I am using will not properly process that array if it contains ints instead of strings.

Most of the time, this will produce proper array containing only strings:

json_encode($data)

Even if $data contains just numbers, I usually get this

["3","7","8"]

Sometimes though, I get results like this (note the zero):

["9691","1792","26","1","4","15",0,"1"]

or this

[16171,15470,10390,7585]

(Note, this is obviously different data to illustrate what's going on). I need to enforce json_encode to treat the array values as strings. I know there's the opposite option JSON_NUMERIC_CHECK which enforces numbers. Does the equivalent really not exist? Seems my only option is to process the array again on the JavaScript end, which, while possible, somewhat breaks the encapsulation of my objects.


It would be nice if there was the opposite of JSON_NUMERIC_CHECK but it doesn't look like there is.

Why can't you ensure the data is of the correct type in your php, before encoding it?

This might mean you have to cast it manually to strings...


在数组中定义它们作为字符串,或者如果它来自其他地方:

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

如果在函数调用中指定了一个标志, json_decode()可以将大整数转换为字符串:

$array = json_decode($json, true, 512, JSON_BIGINT_AS_STRING)
链接地址: http://www.djcxy.com/p/47796.html

上一篇: 如何在json中存储日文字符

下一篇: 编码来创建字符串