2

I am trying to create an a JSON response in this format:

{
  "id": "",
  "goalLink": [{
       "iconUrl": "",
       "title": ""
  }]
}

I declared the variables as

$id;
$goalLink = [];

Then within a constructor i created

$this->id = 123;
$this->goalLink = [
     'iconUrl' => null,
     'title' => null
];

now when i do something like this in a function

public function example() {
    $client = API::client();
    $url = "some url here";
    $data = [
        'id' => $this->id,
        'goalLink' => [
            'iconUrl' => $this->goalLink['iconUrl'],
            'title' => $this->goalLink['title'] 
        ] 
    ];
    $client->post($url, ['json' => $data]);

}

but this is the $data format what the example() is sending to the API

{
  "id": "",
  "goalLink": {
       "iconUrl": "",
       "title": ""
  }
}

I checked in various other forums but could not find a solution. Can someone please help me out here. I am not sure where i am going wrong.

8
  • 1
    The problem is that the fields are empty ? Commented Nov 15, 2015 at 11:56
  • no u see above the format of the json it has a [ ] after goalLink: ... Which basically means its a dynamic array.. but i am not able to pass data in that format i am getting a { } after goalLink: ... Commented Nov 15, 2015 at 12:04
  • try to do: $client->post( $url, [ 'json' => json_encode($data) ] ); Commented Nov 15, 2015 at 12:05
  • 1
    Reading here json.org I would say it is not possible. {} are used to indicate objects = name/value pairs, like so { "name" : "value" } and [] are used to indicate arrays = collections of values, like so [ "value1", "value2"]. So from what I understand you're trying to use [] where JSON says it uses {}. My question is why? Commented Nov 15, 2015 at 12:16
  • 1
    3v4l.org/4jp5l Commented Nov 15, 2015 at 12:29

1 Answer 1

1

Wrapping your associative array with iconUrl and title inside an indexed array would provide the additional wrapper.

public function example() {
    $client = API::client();
    $url = "some url here";
    $data = [
        'id' => $this->id,
        'goalLink' => [
            [
                'iconUrl' => $this->goalLink['iconUrl'],
                'title' => $this->goalLink['title'] 
            ]
        ]
    ];
    $client->post($url, ['json' => $data]);
}
Sign up to request clarification or add additional context in comments.

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.