0

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 .'}';

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

That was it, thanks a lot! also: $json_array[] = $activity_array;
json_encode returns a string, so your "bits of JSON" is just a string. You're just encoding an array of strings.
1

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;

Comments

0

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)
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.