创建遵循 JSON:API 约定的正确 JSON 输出



我正在尝试解析存储在数据库中的一些JSON,对其进行转换,然后将其发送到第三方API(通过webhook)。我目前停留在 JSON 输出格式。我正在尝试遵循JSON:API的标准。

这是我从数据库列fields.content输入:

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

如您所见,这是一个由对象组成的 JSON 数组。每个对象表示一行,每个键表示一列。这可以像这样可视化:

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

在我的模型Field.php中,我使用Laravel铸造,如下所示:

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

它会自动将 json 字符串转换为数组:

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

返回:

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"
]
]

因此,请考虑我对这个数组执行某些操作,例如对单词执行替换PagetoSection

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

这将返回:

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"
]
]

我现在想更新我的数据库fields.content,以反映此更改。但是,当将其重新保存到数据库时,例如:


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

它现在保存为数组数组:

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

这意味着当我通过我的 webhook 发送它时,它不再遵循与开始时相同的 JSON 模式。

我试图json_encode数组,例如:

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

但这不会产生所需的输出/有效 JSON。

谁能帮助我如何使用 Laravel/PHP 转换我的 JSON 对象,并将其重新保存到我的数据库中并保持初始有效的 JSON:API 格式?

完成转换后:

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

现在您可以使用以下代码重新格式化:

$result"[";
foreach ($out as $value) {
$string = json_encode($value);
$string = str_replace('[', '{', $string);
$string = str_replace(']', '}', $string);
$result .= $string .",";
}
$result= rtrim($result, ',');
$result.= "]";
echo $result;
// [{"Section 1, col 1.","",""},{"","Section 1, col 2.",""},{"","","Section 1, col 3"}]

结果是绝对正确的。这是有效的数组表示形式。它是0,1...你有一个数组索引,根据 PHP 在序列化为字符串时不会反映。

怎么办?

直接强制转换为对象(JSON 是对象而不是数组)。

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

若要将$content转换为循环,可以使用以下内容而不是dd

$content = json_decode(json_encode($content), true);

要进行解析,请尝试以下操作:

$out = [];
$i = 0;
foreach($content as $con){
$result = [];
foreach ($con as $col => $rows) {
$result[$col] = str_replace('Page', 'Section', $rows);
}
$out = array_merge($out, [$i => $result]);
}
$out = json_encode($out);
// Loose the dd($out) part.

免责声明:我没有尝试过。

最新更新