[英]remove backslash from json string
我從服務器響應中得到以下 json 字符串:
"\"[\n {\n \"id\": \"1\",\n \"mid\": \"1\",\n \"num\": \"1\",\n \"type\": \"wgp\",\n \"time_changed\": \"time\",\n \"username\": \"aaa\"\n }\n ]\""
我需要將其重新格式化為:
"{ { "id": "1", "mid": "1", "num": "1", "type": "wgp", "time_changed": "time", "username": "aaa" } }
這是我的嘗試
$str = substr($str, 2);
$str = "{".$str;
$str = substr($str,0, strlen($str) - 3);
$str = $str . " }";
$str = trim(preg_replace('/\s\s+/', ' ', $str));
它給了我
"{ { \"id\": \"1\", \"mid\": \"1\", \"num\": \"1\", \"plating_type\": \"wgp\", \"time_changed\": \"time\", \"username\": \"09122099111\" } }"
我無法刪除我試過的反斜杠
$str= preg_replace('/\\\"/', '', $str);
$str = str_replace('\\', '', $str);
stripslashes ()
但他們都沒有工作
您可以嘗試以下方式來實現您所需要的,
$jsonString = '\"[\n {\n \"id\": \"1\",\n \"mid\": \"1\",\n \"num\": \"1\",\n \"type\": \"wgp\",\n \"time_changed\": \"time\",\n \"username\": \"aaa\"\n }\n ]\"';
$jsonString = str_replace('\\n', '', $jsonString); // First remove the new line characters in the json string
$jsonString = str_replace('\\', '', $jsonString); // Replace backslash with empty string
echo preg_replace('!\s+!', ' ', $jsonString); // Replace multiple spaces with one
所以 output 是,
“[ { “id”:“1”,“mid”:“1”,“num”:“1”,“type”:“wgp”,“time_changed”:“time”,“用戶名”:“aaa” }]"
您不應該收到包含在\"\"
中的字符串,否則它將是無效的 json 並且沒有理智的 API 會產生它。 (如果不幸的是,請聯系作者或刪除前 2 個字符和后兩個字符)。
那么這是完全有效的 JSON,所以你可以將它傳遞給 json_decode,然后再次重新編碼,不需要剝離空格。
<?php
$json = "[\n {\n \"id\": \"1\",\n \"mid\": \"1\",\n \"num\": \"1\",\n \"type\": \"wgp\",\n \"time_changed\": \"time\",\n \"username\": \"aaa\"\n }\n ]";
echo json_encode(json_decode($json));
這將產生您想要的結果:
[{"id":"1","mid":"1","num":"1","type":"wgp","time_changed":"time","username":"aaa"}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.