Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

javascript - Force json_encode to create strings of numeric values in a flat array

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 integers 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...