首页 > 解决方案 > 如何对包含 json 字符串元素的数组进行 json_encode 编码?输出不应包含反斜杠“\”

问题描述

例如

$json_string = '{"employee" : { "name" : "test","id" : "1"}}';

    $array = [
                "center"    => "Mumbai",
                "data"      =>  $json_string
    ];

  //echo json_encode($array,JSON_PRETTY_PRINT);
  //echo json_encode($array,JSON_UNESCAPED_SLASHES);
  echo json_encode($array,JSON_UNESCAPED_UNICODE);

它在 json 字符串中给出以下带有反斜杠的输出:

{
 "center": "Mumbai",
 "data": "{\"employee\" : { \"name\" : \"test\",\"id\" : \"1\"}}"
}

即使我用 JSON_PRETTY_PRINT,JSON_UNESCAPED_SLASHES,JSON_UNESCAPED_UNICODE 尝试了 json_encode 但同样的输出即将到来

我想要实现的输出是

{
 "center": "Mumbai",
 "data": { "employee" : { "name" : "test","id" : "1"}}

}

编辑

感谢您的回复,我接受这两个答案,两者都肯定会解决我的问题。


编辑这个问题,因为我的要求有点不同,对此我深表歉意。实际上我正在使用 Lumen API 并且我正在从数据库中获取记录,并且表包含一个 MYsql JSON 列,其他是普通的 mysql 列。例如 test_json 表有一个 json 数据类型为“employee_details_json”的列

CREATE TABLE `test_json` (
`employee_id` int(11) NOT NULL AUTO_INCREMENT,
 `emplyee_name` varchar(45) DEFAULT NULL,
`employee_details_json` json DEFAULT NULL,
`status` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`employee_id`)
);

从这个表中检索数据并作为 json 响应发回对我来说是一个具有挑战性的部分。Bcoz Lumen 将整个数组转换为 json Lumen json 响应,将反斜杠添加到 json 列。这是一个表的示例,其中有许多表包含 json 列。这就是为什么我不能在编码之前硬编码列名来解码 json。

抱歉英语不好。提前致谢

标签: phparraysjsonlumen

解决方案


尝试这个

$json_string = '{"employee" : { "name" : "test","id" : "1"}}';
$array = [
     "center"    => "Mumbai",
     "data"      =>  json_decode($json_string)
];
echo json_encode($array);

输出

{"center":"Mumbai","data":{"employee":{"name":"test","id":"1"}}}

更新 以下是我在 PHP 中的操作方式

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$response = array();
$sql = "SELECT * FROM test_json WHERE employee_id = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $response["success"] = 1;
    // output data of each row
    $a = 0;
    while($row = $result->fetch_assoc()) {
        $row["employee_details_json"] = json_decode($row["employee_details_json"]);
        $response["data"][$a] = $row;
        $a++;
    }
}
echo json_encode($response);
$conn->close();

/*
In Lumen I guess you can achieve this by
I don't know if its the proper way as i never used this framework but you can give it a try
*/
$results = DB::select('SELECT * FROM test_json WHERE employee_id = :employee_id', ['employee_id' => 1]);
$a = 0;
foreach ($results as $row) {

    $results[$a]->employee_details_json = json_decode($row->employee_details_json);
    $a++
}
echo json_encode($results);

推荐阅读