假设我有这样的JSON:
{
id: 1,
somevalue: "text"
}我想通过PHP函数json_encode来创建这个JSON。我可以很容易地将这个JSON转换为:
{
"id": "1",
"somevalue": "text"
}或者,使用JSON_NUMERIC_CHECK格式,其中"id“将是数字,但"somevalue”可以是数字或文本,具体取决于其内容。
如何才能使JSON中的"somevalue“始终为文本格式(带引号)。我会用其他语言来解析它,这一点很重要。
发布于 2012-11-21 05:24:17
要使somevalue始终为“文本”格式,请执行以下操作:
$somevalue1 = 1;
$somevalue2 = "text";
$json1 = array("id" => 1, "somevalue" => (string) $somevalue1);
$json2 = array("id" => 1, "somevalue" => (string) $somevalue2);
echo json_encode($json1); // outputs {"id":1,"somevalue":"1"}
echo json_encode($json2); // outputs {"id":1,"somevalue":"text"}发布于 2012-11-21 05:14:42
确保将您希望为非字符串的值(如int或boolean)输入到源数组中:
<?php
$a = array('id' => 1, 'really' => true, 'somevalue' => 'text');
var_dump( json_decode( json_encode( $a ) ) );给出预期:
object(stdClass)#1 (2) {
["id"]=>
int(1)
["really"]=>
bool(true)
["somevalue"]=>
string(4) "text"
}编辑
如果您希望它始终是字符串,则将数组中的字符串放在第一位:
<?php
$a = array('id' => '1', 'really' => 'true', 'somevalue' => 'text');
var_dump( json_decode( json_encode( $a ) ) );会给你
object(stdClass)#1 (3) {
["id"]=>
string(1) "1"
["really"]=>
string(4) "true"
["somevalue"]=>
string(4) "text"
}但这就扼杀了拥有不同变量类型的全部目的。
你可以在json编码之前转换数组:
<?php
$a = array('id' => 1, 'really' => true, 'somevalue' => 'text');
$tmp = array();
foreach( $a as $key=>$val ) {
$tmp[$key] = (string)$val;
}
var_dump( json_decode( json_encode( $tmp ) ) );最终会放弃:
object(stdClass)#1 (3) {
["id"]=>
string(1) "1"
["really"]=>
string(1) "1"
["somevalue"]=>
string(4) "text"
}发布于 2013-03-08 23:33:03
在PHP> 5.3.3.上,可以使用json_decode($array,JSON_NUMERIC_CHECK);
如果你没有PHP 5.3.3或更高版本,我写了这个递归函数:
function json_encode_with_numbers($array) {
if(is_array($array)) {
if(count($array)>0 && array_keys($array) !== range(0, count($array) - 1)) {
echo '{';
$isFirst = true;
foreach($array as $key=>$item) {
if(!$isFirst) {
echo ",";
}
echo '"'.$key.'":';
json_encode_with_numbers($item);
$isFirst = false;
}
echo '}';
} else {
echo '[';
$isFirst = true;
foreach($array as $item) {
if(!$isFirst) {
echo ",";
}
json_encode_with_numbers($item);
$isFirst = false;
}
echo ']';
}
} else {
if(is_numeric($array)) {
echo $array;
} elseif ($array == null) {
echo "null";
} else {
echo '"'.str_replace(array('"', '\\'), array('\"', '\\\\'), $array).'"'; // escape special chars
}
}
}https://stackoverflow.com/questions/13482200
复制相似问题