首页 > 解决方案 > 在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

解决方案


假设你有一个 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);
?>

您的数据非常损坏。您应该修复生成它的代码,而不是在此阶段将其破解为合理的东西。


推荐阅读