mercredi 10 juillet 2019

Creating a correct JSON output that follows JSON:API convention

I am trying to parse some JSON that is stored in my database, transform it and then send it to a 3rd party API (by webhook). I am currently stuck at the JSON output format. I am trying to follow the standards of JSON:API.

This is my input from my database column fields.content:

[{"0": "Page 1, col 1.", "1": "", "2": ""}, {"0": "", "1": "Page 1, col 2.", "2": ""}, {"0": "", "1": "", "2": "Page 1, col 3"}]

As you can see, this is a JSON array that consists of objects. Each object represents a row, and each key represents a column. This can be visualed like:

___________________________________________________
| COL 1         | COL 2          | COL 3          |
___________________________________________________
| Page 1, col 1.|                |                |
|---------------|----------------|----------------|
|               |Page 1, col 2.  |                |
|---------------|----------------|----------------|
|               |                | Page 1, col 3. |
---------------------------------------------------

In my model Field.php, I use Laravel casting like:

protected $casts = [
     'content' => 'array'
];

Which automatically converts the json string to an array:

dd($content) //$content is the json string from the database

Returns:

array:3 [▼
  0 => array:3 [▼
    0 => "Page 1, col 1."
    1 => ""
    2 => ""
  ]
  1 => array:3 [▼
    0 => ""
    1 => "Page 1, col 2."
    2 => ""
  ]
  2 => array:3 [▼
    0 => ""
    1 => ""
    2 => "Page 1, col 3"
  ]
]

So consider that I do something with this array, like performing a replace on the word Page to Section:

$out = [];
foreach ($content as $col => $rows) {
    $out[$col] = str_replace('Page', 'Section', $rows);
}
dd($out);

This returns:

array:3 [▼
  0 => array:3 [▼
    0 => "Section 1, col 1."
    1 => ""
    2 => ""
  ]
  1 => array:3 [▼
    0 => ""
    1 => "Section 1, col 2."
    2 => ""
  ]
  2 => array:3 [▼
    0 => ""
    1 => ""
    2 => "Section 1, col 3"
  ]
]

I now want to update my database fields.content, to reflect this change. However when re-saving it to the database like:


$field = Field::find(1);
$field->content = $out;
$field->save();

It is now saved as an array of arrays:

[["Section 1, col 1.", "", ""], ["", "Section 1, col 2.", ""], ["", "", "Section 1, col 3"]]

This means that when I send this through my webhook, it no longer follows the same JSON schema like it started out with.

I have tried to json_encode the array, like:

$field->content = [json_encode($out, JSON_FORCE_OBJECT)]

But this doesn't produce the desired output/valid JSON.

Can anyone help me on how to transform my JSON object with Laravel/PHP, and re-save it to my database and keeping the initial valid JSON:API format?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire