Reputation: 1299
Im trying to create this with the php encode function:
{
"foo": [
{
"bar": "111"
}
]
}
But all i can manage with some php arrays and json encoding is this:
{
"foo": [
"{
\"bar\":184530"
}"
]
}
Obviously i don't want the object as a string but as an object, so without quotes.
Here's my 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 .'}';
Upvotes: 0
Views: 1119
Reputation: 1975
You can use this little PHP library. It sends the headers and give you an object to use it easily.
It looks like :
<?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)
?>
Upvotes: 0
Reputation: 227180
json_encode
takes a PHP array, and converts it to JSON. You don't build the array as JSON, just build a normal array, and then json_encode
it.
For example to make the object in your question, you would do this:
$arr = array('foo' => array(
array('bar' => 111)
));
echo json_encode($arr);
So, just build the array, and then 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;
Upvotes: 1
Reputation: 943097
Don't encode bits of your data structure as JSON. Only encode the final data structure. Remove this line:
$activity_json = json_encode($activity_array);
That causes you to have an array encoded as JSON stored in an array which is also encoded as JSON.
You want an array (encoded as JSON) that contains an array (not bits of JSON).
Upvotes: 5