例如
$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的原因。
对不起,英语不好。预先感谢
答案 0 :(得分:1)
尝试一下
$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);
答案 1 :(得分:0)
您可以选择@Ussaid提供的第一个解决方案或其他方法,而无需对字符串进行解码,然后对其进行编码可能会花费更多时间。获得预期结果的另一种方法是使用反斜杠:
以下是具有所需输出的示例:
$json_string = '{"employee" : { "name" : "test","id" : "1"}}';
$array = [
"center" => "Mumbai",
"data" => $json_string
];
echo stripslashes(json_encode($array));
希望它对您有所帮助,并且幸福。