在PHP/Laravel中发送JSON数据时,破折号("-")本身并不是特殊字符,可以直接包含在JSON字符串中。JSON规范允许在字符串值中使用破折号,但需要注意以下几点:
return response()->json([
'key-with-dash' => 'value-with-dash',
'normalKey' => 'normal-value'
]);
$data = [
'key-with-dash' => 'value-with-dash',
'array-with-dash' => ['item-1', 'item-2']
];
return response(json_encode($data), 200)
->header('Content-Type', 'application/json');
前端JavaScript接收时不需要特殊处理:
fetch('/api/endpoint')
.then(response => response.json())
.then(data => {
console.log(data['key-with-dash']); // 访问带破折号的键
});
原因:可能是键名未加引号或编码不正确
解决:
// 错误示例 - 键名不加引号会导致JSON无效
// {key-with-dash: "value"}
// 正确示例
$data = ['key-with-dash' => 'value'];
json_encode($data); // 自动处理引号
原因:json_encode()默认会转义斜杠等字符
解决:
json_encode($data, JSON_UNESCAPED_SLASHES);
原因:默认会转义非ASCII字符
解决:
json_encode($data, JSON_UNESCAPED_UNICODE);
完整控制器示例:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class JsonController extends Controller
{
public function sendJson()
{
$data = [
'user-data' => [
'first-name' => 'John',
'last-name' => 'Doe',
'email' => 'john-doe@example.com'
],
'product-codes' => ['PROD-001', 'PROD-002']
];
return response()->json($data);
}
public function sendRawJson()
{
$data = [
'key-with-dash' => 'value-with-dash',
'normalKey' => 'normal-value'
];
return response(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 200)
->header('Content-Type', 'application/json');
}
}
路由示例:
Route::get('/json-data', [JsonController::class, 'sendJson']);
Route::get('/raw-json', [JsonController::class, 'sendRawJson']);