php - 在php中将反斜杠json字符串转换为真实的json数组
问题描述
我的数据库中存储了以下内容:
"{\"id\":10,\"name\":\"Foobar\",\"sheep\":5,\"type\":\"test\",\"created_at\":\"2017-12-20 17:51:41\",\"updated_at\":\"2017-12-20 17:51:41\",\"title\":\"Sheep\"},{\"id\":13,\"name\":\"Foobar\",\"price\":5,\"type\":\"day\",\"created_at\":\"2017-12-21 18:02:28\",\"updated_at\":\"2017-12-21 18:02:28\",\"title\":\"Hello\"},{\"id\":15,\"name\":\"Car\",\"price\":5,\"type\":\"day\",\"created_at\":\"2018-03-16 11:16:59\",\"updated_at\":\"2018-03-16 11:16:59\",\"title\":\"Car\"}"
但这不是一个有效的 JSON 字符串。如何将此字符串转换为真正的 Json 数组?
这是使用的代码:
$(document).on('click change', '.select-list', function(e) {
e.preventDefault();
var options = [];
$('.optionitem').each(function(foo) {
if($(this).is(':checked')) {
options.push($(this).val());
} else {
}
});
$('#list').val(options);
// This list is send via jQuery/Ajax to server and parsed like this when saving:
// <?php $request['list'] = json_decode([$request['list']]); ?>
});
解决方案
假设你有一个 PHP 字符串作为值…</p>
运行它json_decode
会将其转换为带有一组逗号分隔的 JSON 文本的 PHP 字符串,这些文本表示对象。
用它包装[
然后]
运行它json_decode
会将其转换为 PHP 数组。
<?php
$original_json = <<<END
"{\"id\":10,\"name\":\"Foobar\",\"sheep\":5,\"type\":\"test\",\"created_at\":\"2017-12-20 17:51:41\",\"updated_at\":\"2017-12-20 17:51:41\",\"title\":\"Sheep\"},{\"id\":13,\"name\":\"Foobar\",\"price\":5,\"type\":\"day\",\"created_at\":\"2017-12-21 18:02:28\",\"updated_at\":\"2017-12-21 18:02:28\",\"title\":\"Hello\"},{\"id\":15,\"name\":\"Car\",\"price\":5,\"type\":\"day\",\"created_at\":\"2018-03-16 11:16:59\",\"updated_at\":\"2018-03-16 11:16:59\",\"title\":\"Car\"}"
END;
$json_one = "[" . json_decode($original_json, TRUE) . "]";
$array = json_decode($json_one, TRUE);
print_r($array);
?>
您的数据非常损坏。您应该修复生成它的代码,而不是在此阶段将其破解为合理的东西。
推荐阅读
- javascript - Google Maps V3 中的单独折线
- python - discord.py remove_roles 不起作用
- php - 数组到有效的 json PHP
- google-cloud-platform - 授予 IAM 用户对 API 凭证的访问权限
- javonet - java - 如何避免在javonet中对数组中的基元进行自动装箱
- mysql - SQL减去2个select语句的结果
- java - 如何使流报告错误和下一步
- java - KeyEvent.getKeyText(keycode); 不明白它等于什么
- ios - 将 MBTiles 包转换为 illustrator 矢量信息
- ios - 如何解决目标 C 中的 sqlite 错误?