问题
I have saved some Json data in a MySQL column. While fetching the data to a Laravel Blade application the json fields are all escaped. Hence, I am facing issues while reading the json data.
[
{
"id": "1",
"json_backup": "{\"id\":\"2\",\"organization_id\":\"1\",\"amount\":\"7800.00\",\"date\":\"2015-05-11\",\"created_at\":\"2015-05-11 07:20:45\",\"updated_at\":\"2015-05-11 07:20:45\"}",
"ip": "127.0.0.1",
"created_at": "2015-05-12 12:21:16",
"updated_at": "2015-05-12 12:21:16"
}
]
The json_backup field in the above example is escaped. How do I ensure that this field is not escaped.
Code to fetch the data
$activity = Activity::find(1);
In the View:
@foreach ($activities AS $activity)
@foreach($activity->json_backup AS $order)
@endforeach
@endforeach
Error:
Invalid argument supplied for foreach()
Any help would be much appreciated.
回答1:
@saaz When you are storing the JSON in MySQL, use
json_encode($json_backup, JSON_UNESCAPED_SLASHES)
HTH
回答2:
This error is coming on the second foreach
section.
Please try it in somewhat this way.
$json = json_decode($activity->json_backup, true);
This would work but can't say it definitely. And even if you have problem refactor the code and create a class with following code:
function escapeJsonString($value) {
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
And simply say
$json = escapeJsonString($activity->json_backup);
This one would definitely work. Hope so this helps.
来源:https://stackoverflow.com/questions/30194110/database-json-column-returning-escaped-string-in-laravel-blade