Programing

PHP json_encode 인코딩 숫자를 문자열로

lottogame 2020. 6. 28. 18:26
반응형

PHP json_encode 인코딩 숫자를 문자열로


PHP json_encode 함수에 문제가 있습니다. 숫자를 문자열로 인코딩합니다. 예 :

array('id' => 3)

된다

"{ ["id": "3", ...)

js가이 값을 만나면이를 문자열로 해석하고 숫자 연산이 실패합니다. 누구든지 json_encode숫자를 문자열로 인코딩 하지 못하게하는 방법을 알고 있습니까? 감사합니다!


나는 매우 빠른 테스트를 수행했습니다.

$a = array(
    'id' => 152,
    'another' => 'test',
    'ananother' => 456,
);
$json = json_encode($a);
echo $json;

내가 실수하지 않으면 이것은 당신이 묘사 한 것과 같습니다.

그리고 나는 출력으로 얻고있다 :

{"id":152,"another":"test","ananother":456}

따라서이 경우 정수는 문자열로 변환되지 않았습니다.


아직도, 이것은 우리가 사용하는 PHP 버전에 따라 다를 수 있습니다 : PHP 버전에 따라 몇 가지 json_encode 관련 버그가 수정되었습니다 ...

이 테스트는 PHP 5.2.6에서 이루어졌습니다. PHP 5.2.9와 5.3.0에서도 마찬가지입니다. 테스트 할 다른 5.2.x 버전이 없지만 :-(

어떤 버전의 PHP를 사용하고 있습니까? 아니면 테스트 사례가 게시 한 예보다 더 복잡합니까?

아마 http://bugs.php.net/의 하나의 버그 보고서 와 관련이있을 수 있습니까? 예를 들어, 버그 # 40503 : json_encode 정수 변환이 PHP와 일치하지 않습니까?


아마 버그 # 38680은 BTW, 당신도 관심을 수 있을까?


PHP 5.3.3부터 숫자 자동 변환을위한 플래그 가 있습니다 (options 매개 변수는 PHP 5.3.0에서 추가되었습니다) :

$arr = array( 'row_id' => '1', 'name' => 'George' );
echo json_encode( $arr, JSON_NUMERIC_CHECK ); // {"row_id":1,"name":"George"}

나도 마찬가지로 DB (PostgreSQL)에서 읽고 있었고 모든 것이 문자열이었습니다. 우리는 각 행을 반복하고 최종 결과 배열을 만들기 위해 행을 사용하므로

$result_arr[] = array($db_row['name'], (int)$db_row['count']);

루프 내에서 정수 값으로 강제합니다. 내가 할 때 json_encode($result_arr)지금, 그것은 정확하게 숫자로 포맷합니다. 이를 통해 데이터베이스에서 나오는 숫자와없는 숫자를 제어 할 수 있습니다.

편집하다:

json_encode()함수는 또한 JSON_NUMERIC_CHECK플래그를 두 번째 인수로 사용하여 즉시이를 수행 할 수 있습니다. 이 사용자 예제에 나와있는 설명서 (아래에 복사)에 표시된대로주의해서 사용해야합니다. http://uk3.php.net/manual/en/function.json-encode.php#106641

<?php
// International phone number
json_encode(array('phone_number' => '+33123456789'), JSON_NUMERIC_CHECK);
?>

그런 다음이 JSON을 얻습니다.

{"phone_number":33123456789}

동일한 문제가 발생합니다 (PHP-5.2.11 / Windows). 이 해결 방법을 사용하고 있습니다

$json = preg_replace( "/\"(\d+)\"/", '$1', $json );

따옴표로 묶인 모든 음수가 아닌 정수를 숫자 자체로 바꿉니다 ( ' "42"'는 '42'가 됨).

PHP manual의이 주석 도 참조하십시오 .


시험 $arr = array('var1' => 100, 'var2' => 200);
$json = json_encode( $arr, JSON_NUMERIC_CHECK);

그러나 PHP 5.3.3에서만 작동합니다. 이 PHP json_encode 변경 로그를보십시오. http://php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-changelog


다음 테스트는 유형을 문자열로 변경하면 json_encode ()가 숫자를 JSON 문자열 (즉, 큰 따옴표로 묶음)로 반환하는지 확인합니다. settype (arr [ "var"], "정수") 또는 settype ($ arr [ "var"], "float")을 사용하여 수정하십시오.

<?php

class testclass {
    public $foo = 1;
    public $bar = 2;
    public $baz = "Hello, world";
}

$testarr = array( 'foo' => 1, 'bar' => 2, 'baz' => 'Hello, world');

$json_obj_txt = json_encode(new testclass());
$json_arr_txt = json_encode($testarr);

echo "<p>Object encoding:</p><pre>" . $json_obj_txt . "</pre>";
echo "<p>Array encoding:</p><pre>" . $json_arr_txt . "</pre>";

// Both above return ints as ints. Type the int to a string, though, and...
settype($testarr["foo"], "string");
$json_arr_cast_txt = json_encode($testarr);
echo "<p>Array encoding w/ cast:</p><pre>" . $json_arr_cast_txt . "</pre>";

?>

완성도를 높이기 위해 (아직 설명을 추가 할 수 없으므로)이 세부 정보를 다른 답변으로 추가하겠습니다.

(Edit: To be read after realizing that the source data (i.e. in the OP's case, database result set) could be the problem (by returning numeric columns as strings), and json_encode() in fact was not the source of the problem)

Manual pages of both "mysql_fetch_array":

Returns an array of strings that corresponds to the fetched row,

... and "mysql_ fetch_ row":

Returns an numerical array of strings that corresponds to the fetched row

clearly states that; the entries in the returned array will be strings.

(I was using the DB class in phpBB2 (yes I know, it's obsolete!), and "sql_fetchrow()" method of that class uses "mysql_fetch_array()")

Not realizing that, I also ended up finding this question, and understanding the problem! :)

As Pascal Martin stated above in his follow-up comments, I believe a solution that takes care of the "incorrect type" problem at the source (i.e. by using the "mysql_field_type()" function and doing the casting right after fetch, (or other fetch methods like "object"?)) would be the better in general.


So Pascal MARTIN isn't getting enough credit here. Checking for numeric values on every JSON return is not feasable for an existing project with hundreds of server side functions.

I replaced php-mysql with php-mysqlnd, and the problem went away. Numbers are numbers, strings are strings, booleans are boolean.


I also had the same problem processing data from the database. Basically the problem is that the type in the array to convert in json, is recognized by PHP as a string and not as integer. In my case I made a query that returns data from a DB column counting row. The PDO driver does not recognize the column as int, but as strings. I solved by performing a cast as int in the affected column.


$rows = array();
while($r = mysql_fetch_assoc($result)) {
    $r["id"] = intval($r["id"]); 
    $rows[] = $r;
}
print json_encode($rows);  

it is php version the problem, had the same issue upgraded my php version to 5.6 solved the problem


Casting the values to an int or float seems to fix it. For example:

$coordinates => array( 
    (float) $ap->latitude,
    (float) $ap->longitude 
);

You can use (int) if any issue occurs!! It will work fine.


Well, PHP json_encode() returns a string.

You can use parseFloat() or parseInt() in the js code though:

parseFloat('122.5'); // returns 122.5
parseInt('22'); // returns 22
parseInt('22.5'); // returns 22

Just run into the same problem and was the database returning the values as strings.

I use this as a workaround:

$a = array(
    'id' => $row['id'] * 1,
    'another' => ...,
    'ananother' => ...,
);
$json = json_encode($a);

That is multiplying the value by 1 to cast it into a number

Hope that helps someone


json_encode serializes some data structure in JSON format to be send across the network. Therefore all content will be of the type string. Just like when you receive some parameter from $_POST or $_GET.

If you have to make numeric operations on the values sent, just convert them to int first (with the intval() function in PHP or parseInt() in Javascript) and then execute the operations.


Like oli_arborum said, I think you can use a preg_replace for doing the job. Just change the command like this :

$json = preg_replace('#:"(\d+)"#', ':$1', $json);

참고URL : https://stackoverflow.com/questions/1390983/php-json-encode-encoding-numbers-as-strings

반응형