1

We're currently having an Android-App access some of the entries of our Craft-based website. We are currently still using a self built API, and for easier creation of new API-Calls we are trying to migrate over to Pixel & Tonic's Element API plugin.

The entries (or the blocks of a Matrix-field of that entry, to be more precise) are accessed like so:

'api/alloverlist' => function() { // GET ALLOVER-CHALLENGES
        return [
            'elementType' => ElementType::Entry,
            'criteria' => [
                'section' => 'challenges',
                ],
            'paginate' => false,
            'first' => true,
            'transformer' => function(EntryModel $entry){

                $allOverChallenges = [];
                foreach ($entry->allOverChallenge as $challenge){
                    $allOverChallenges[] = [
                        'elementId' => $challenge->id,
                        'field_allOverChallenge_allOverName' => $challenge->allOverName,
                    ];
                }

                return [
                    $allOverChallenges
                ];
            },
        ];
    },

The returned JSON-String has the following appearance:

[
[
    {
        "elementId": "1298",
        "field_allOverChallenge_allOverName": "Dein schönster Sonnenaufgang"
    },
    {
        "elementId": "1310",
        "field_allOverChallenge_allOverName": "AllOverChallenge2"
    },
    {
        "elementId": "1318",
        "field_allOverChallenge_allOverName": "Allover Challenge 3"
    }
]
]

However, the Android-App accepts the JSON-String just with single square-brackets, like so:

[
   {
     "key":"value",
      ...
   },

   {
     "key":"value",
      ...
   }
]

For the sake of not having to change the existing Android-App, is it somehow possible to remove the additional square brackets?

Thanks.

1 Answer 1

3

Though I don't know the Element API, have you tried

    return $allOverChallenges;

instead of

    return [
        $allOverChallenges
    ];

It looks like you are simply adding these brackets (Array) on the return.

1
  • Well, that sure was easy and obvious, wasn't it? It works, thank you! I feel really dumb now :) Aug 15, 2017 at 10:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.