PHP-从无效的json中删除密钥

时间:2015-02-28 18:14:08

标签: php json

我是php新手,不知道如何处理无效的json。 所以我想删除那些具有无效字符串值的键

此处tag_listdescription包含无效的字符串值。

$json='{
    "kind": "track",
    "id": 132453675,
    "created_at": "2014/02/01 02:01:11 +0000",
    "user_id": 895073,
    "duration": 323242,
    "commentable": true,
    "state": "finished",
    "original_content_size": 7745028,
    "last_modified": "2014/02/23 15:48:45 +0000",
    "sharing": "public",
    "tag_list": "hi " how are",
    "permalink": "leaman",
    "streamable": true,
    "embeddable_by": "all",
    "downloadable": false,
    "purchase_url": null,
    "label_id": null,
    "purchase_title": null,
    "genre": "Pop",
    "title": "Leaman",
    "description": "what"" is for",
    "label_name": null,
    "release": null,
    "track_type": null,
    "key_signature": null,
    "isrc": null,
    "video_url": null,
    "bpm": null,
    "release_year": null,
    "release_month": null,
    "release_day": null,
    "original_format": "mp3",
    "license": "all-rights-reserved",
    "uri": "https://api.soundcloud.com/tracks/132453675",
    "user": {
        "id": 895073,
        "kind": "user",
        "permalink": "cloudsareghosts",
        "username": "cloudsareghosts",
        "last_modified": "2014/02/13 22:16:09 +0000",
        "uri": "https://api.soundcloud.com/users/895073",
        "permalink_url": "http://soundcloud.com/cloudsareghosts",
        "avatar_url": "https://i1.sndcdn.com/avatars-000005407842-c7dt3c-large.jpg"
    },
    "permalink_url": "http://soundcloud.com/cloudsareghosts/leaman",
    "artwork_url": "https://i1.sndcdn.com/artworks-000069579796-mhc0bg-large.jpg",
    "waveform_url": "https://w1.sndcdn.com/r4xyDo8zqpfU_m.png",
    "stream_url": "https://api.soundcloud.com/tracks/132453675/stream",
    "playback_count": 253,
    "download_count": 0,
    "favoritings_count": 4,
    "comment_count": 0,
    "attachments_uri": "https://api.soundcloud.com/tracks/132453675/attachments",
    "policy": "ALLOW"
}';

那么如何从php中的这个json中删除这些键tag_listdescription

由于

1 个答案:

答案 0 :(得分:0)

似乎双引号混淆了JSON。您必须将这些"替换为\"

所以:  "description": "what"" is for", 应该  "description": "what\"\" is for",

根据您获得JSON的方式,您可以使用PHP str_replace而不是手动执行此操作。 例如,如果此JSON是由您自己的脚本创建的,则可以对其进行编辑以确保它输出反斜杠。 (循环对象并通过\"在值中关联双引号。)

修改 PHP中的示例:

$json = preg_replace_callback(
    '/^([^"]*"[^*]+": )"(.*?)"(.*)$/mU',
    function ($matches) {
        return $matches[1].'"'.str_replace('"', '\"', $matches[2]).'"'.$matches[3];
    },
    $json);

preg_replace_callback将值声明中的双引号替换为\"。请在此处查看:https://eval.in/294426