Search code examples
jsonlithium

Get Li3 to return JSON results as an array of objects, not an object of objects


I am trying to utilize the JSON result of a GET request to my Li3 app, but I would like the result to be an array of the returned JSON objects, rather than an object of the JSON objects.

I have the following code in my view file (index.html.php):
print($todos->to('json'));

Which results in each row becoming a JSON object (good), but within an over-arching JSON object.

{
    "1": {
        "id": "1",
        "title": "One",
        "done": "0"
    },
    "2": {
        "id": "2",
        "title": "Two",
        "done": "0"
    },
    "3": {
        "id": "3",
        "title": "Three",
        "done": "0"
    },
    "4": {
        "id": "4",
        "title": "Four",
        "done": "0"
    }
}

I would like to get:

[
    {
        "id": "1",
        "title": "One",
        "done": "0"
    },
    {
        "id": "2",
        "title": "Two",
        "done": "0"
    },
    {
        "id": "3",
        "title": "Three",
        "done": "0"
    },
    {
        "id": "4",
        "title": "Four",
        "done": "0"
    }
]

Note: I've found that this was the case (array of objects) in commit "974469cf25db5cbab61f3e1ff172405f4635032e" of the lithium github project, but with anything after that commit, the result is an object of objects.


Solution

  • Try $todos->to('json', ['indexed' => false]), or, refer to the Media class for direct serialization of JSON without the template.