0

i am struggling with encoding json data

when posting to confluenec it needs to be

{"id":"282072112","type":"page","title":"new page","space":{"key":"BLA"},"body":{"storage":{"value":"<p>This is the updated text for the new page</p>","representation":"storage"}},"version":{"number":2}}'

so in php i created


$data = array('id'=>$siteid, 'type'=>'page', 'title'=>'title of the page');

$data_json = json_encode($data);


print_r ($data_json);

The endresult should look like

{
  "id": "282072112",
  "type": "page",
  "title": "new page",
  "space": {
    "key": "BLA"
  },
  "body": {
    "storage": {
      "value": "<p>This is the updated text for the new page</p>",
      "representation": "storage"
    }
  },
  "version": {
    "number": 2
  }
}

but how can i add the childs etc?

Thanks

  • You could try and `json_decode( $json, true);` your target string, then `print_r()` the result to see how the arrays are nested. – Nigel Ren Apr 02 '20 at 10:23

4 Answers4

2

You can nest data in arrays similarly to what you would to in JavaScript:

$data = [
    'id' => $siteid,
    'type' => 'page',
    'title' => 'new page',
    'space' => [
        'key' => 'BLA',
    ],
    'body' => [
        'storage' => [
            'value' => '<p>...</p>',
            'representation' => 'storage'
        ],
    ],
    'version' => [
        'number' => 2,
    ],
];

// as JSON in one line:
echo json_encode($data);

// or pretty printed:
echo json_encode($data, JSON_PRETTY_PRINT);
jeromegamez
  • 3,348
  • 1
  • 23
  • 36
1
$data = [
  "id" => $siteid,
  "type" => "page",
  "space" => ["key" => "bla"]
 //...
]

You can nest arrays. See also: Shorthand for arrays: is there a literal syntax like {} or []? and https://www.php.net/manual/en/language.types.array.php

Zoldszemesostoros
  • 387
  • 1
  • 3
  • 15
1

Try it

$data_child = array( 'value'=> 'blablabla' );
$data = array('id'=>$siteid, 'type'=>'page', 'title'=>'title of the page', 'child' => $data_child );

$data_json = json_encode($data);
Fabrice Fabiyi
  • 351
  • 6
  • 17
1

You can create nested array this way and the send it after json_encode()

<?php
$preparing_array = array
    (
    "id" => 282072112,
    "type" => "page",
    "title" => "new page",
    "space" => array
    (
        "key" => "BLA"
    ),
    "body" => array
    (
        "storage" => array
        (
            "value" => "<p>This is the updated text for the new page</p>",
            "representation" => "storage"
        )
    ),
    "version" => array
    (
        "number" => 2
    )
);
echo json_encode($preparing_array, JSON_PRETTY_PRINT);
?>

DEMO: https://3v4l.org/16960

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103