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

1
  • You could try and json_decode( $json, true); your target string, then print_r() the result to see how the arrays are nested. Commented Apr 2, 2020 at 10:23

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.