javascriptjsonmoodle

Changing json value order with Javascript


I need a different order of the values of my JSON string. I use php to create a JSON string from a database query that looks like this:

$lbtbs = $DB->get_records('lbtb_eintraege');
$lbtb_json = json_encode($lbtbs, JSON_PRETTY_PRINT);

The database is read out in the “Moodle” system. According to the documentation an array of objects is returned.

My JSON string that I submit using php looks like this:

{id: '1', date: '2024-05-05', start: '1', description: 'fdsfdsfd', standort: 'sz', …}

In Javascript I parse the JSON string with:

this.events = JSON.parse(decodeURI(this.lbtbdata));

However, I need the string to be nested differently. The date should come first, then the ID and the remaining values within the ID. As an example:

[DATE]
 - [ID]
     - [REST DATA]

I tried it like this.

for (const date of Object.keys(this.events)) {
                    for (const id of Object.keys(this.events[date])) {
                        const event = new Event(this.events[date][id]);
                        this.events[date][id] = event;
                    }
                }

I'm still missing a few exercises when it comes to JavaScript. I would therefore be grateful for any suggestion for a solution or for a few keywords to search for!


Solution

  • It would be more efficient to let the server do the work rather than on the client side

    The third parameter for get_records is a sort, so you could sort by date and id

    The fourth parameter is a list of field names, so you could specify the field names if you don't need them all - the first field needs to be a unique value though, the date might not be a unique

    $lbtbs = $DB->get_records('lbtb_eintraege', null, 'date,id', 'id,date,start,description,standort');
    

    See https://moodledev.io/docs/4.4/apis/core/dml#get_records

    Then convert the array to your requirements in PHP

    $data = array();
    
    foreach ($lbtbs as $lbtb) {
        $data[$lbtb->date][$lbtb->id] = array($lbtb->start, $lbtb->description, $lbtb->standort);
    }
    

    Then convert to json

    $lbtb_json = json_encode($data);
    

    Also note: date is a reserved word and shouldn't be used for a column name

    See https://docs.moodle.org/dev/XMLDB_reserved_words