php - 如何对包含 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。
抱歉英语不好。提前致谢
解决方案
尝试这个
$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);
推荐阅读
- indexing - 从打包序列中获取每个序列的最后一项
- react-admin - 如何从 react-admin 框架中的路由中删除哈希
- python - 如何阻止引用对象属性
- java - 如何在Android中使用Opencv检测非静止背景中物体的存在?
- java - 如何仅从数组列表中计算平均值“计算正数而忽略负数)?
- postgresql - 无法评估:评估“除非”子句时出错
- php - 3 位数的碳计数小时数
- biztalk - 交货通知失败问题
- sql - 连接三个具有不同计数总和的表时如何包括上次更新日期
- firebase - 与 firebase 的对话流连接错误:Webhook 调用失败。错误:请求超时