JSON编码问题

时间:2012-01-12 14:48:14

标签: php json

我试图用php编码函数创建它:

{
"foo": [
  {
     "bar": "111"
  }
 ]
}

但我可以管理一些php数组和json编码:

{
"foo": [
    "{
        \"bar\":184530"
    }"
]
}

显然我不希望将对象作为字符串而是作为对象,所以没有引号。

这是我的PHP:

    $stmt->execute();
    $stmt->bind_result($bar);
    while ($stmt->fetch()) {
        $activity_array = array("bar" => $bar);                 
        $activity_json = json_encode($activity_array);
        $json_array[] = $activity_json;
    }

    $json = json_encode($json_array);
    echo '{ "foo": ' .$json .'}';

3 个答案:

答案 0 :(得分:5)

不要将数据结构的位编码为JSON。仅编码最终数据结构。删除这一行:

$activity_json = json_encode($activity_array);

这会导致您将一个编码为JSON的数组存储在一个数组中,该数组也被编码为JSON。

你想要一个包含数组(不是JSON位)的数组(编码为JSON)。

答案 1 :(得分:1)

json_encode接受一个PHP数组,并将其转换为JSON。您不是将数组构建为JSON,只是构建一个普通数组,然后json_encode它。

例如,要在问题中创建对象,您可以这样做:

$arr = array('foo' => array(
    array('bar' => 111)
));
echo json_encode($arr);

所以,只需构建数组,然后echo json_encode($json_array);

$stmt->execute();
$stmt->bind_result($bar);
while ($stmt->fetch()) {
    $activity_array = array("bar" => $bar);
    $json_array[] = $activity_json;
}

$json = json_encode(array('foo' => $json_array));
echo $json;

答案 2 :(得分:0)

您可以使用此little PHP library。它会发送标题并为您提供一个易于使用的对象。

看起来像:

<?php
// Include the json class
include('includes/json.php');

// Then create the PHP-Json Object to suits your needs

// Set a variable ; var name = {}
$Json = new json('var', 'name'); 
// Fire a callback ; callback({});
$Json = new json('callback', 'name'); 
// Just send a raw JSON ; {}
$Json = new json();

// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';

// Add some content
$Json->addContent(new propertyJson('width', '565px'));
$Json->addContent(new textJson('You are logged IN'));
$Json->addContent(new objectJson('An_Object', $object));
$Json->addContent(new arrayJson("An_Array",$arraytest));
$Json->addContent(new jsonJson("A_Json",$jsonOnly));

// Finally, send the JSON.

json_send($Json)
?>
相关问题