如何在 Laravel 中解码 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35955947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:23:57  来源:igfitidea点击:

How to Decode JSON object in Laravel

phpjsonlaravellaravel-5laravel-5.1

提问by Ehsan Ali

I want to decode gallery array JSON objects in Laravel 5.1. my JSON is:

我想在 Laravel 5.1 中解码画廊数组 JSON 对象。我的 JSON 是:

{
  "title": "aaaaaaaaaaaaaaaa",
  "category_id": "1",
  "user_id": "1",
  "gallery": "[{name: \"XCB808tvXNpqXKqekA2HlkJ8H.jpg\",size:5112},{name: \"s6kA6B0e5m1sdSAjPXqNwtiy4.jpg\", size: 13135}]"
}

When I use this code, return me null:

当我使用此代码时,请返回null

public function store(Request $request)
    {
         $json = json_decode($request['gallery'],true);
         return $json;
    }
}

and this is dd($request['gallery'])result

这是dd($request['gallery'])结果

[{'name': "XCB808tvXNpqXKqekA2HlkJ8H.jpg",'size':5112},{'name': "s6kA6B0e5m1sdSAjPXqNwtiy4.jpg", 'size': 13135}]

回答by Moppo

The decoding process is right. I think your problem is you could have a malformed JSON string.

解码过程是正确的。我认为你的问题是你可能有一个格式错误的 JSON 字符串。

Replace the single quotes around property names with double quotes:

用双引号替换属性名称周围的单引号:

[{"name": "XCB808tvXNpqXKqekA2HlkJ8H.jpg","size":5112},{"name": "s6kA6B0e5m1sdSAjPXqNwtiy4.jpg", "size": 13135}]

回答by Tibin Paul

I am not pretty sure about your program flow but as you are injecting Request dependency to the store function, I assume the JSON object is a part of your request. In that case, you can try,

我不太确定您的程序流程,但是当您将请求依赖项注入到 store 函数时,我假设 JSON 对象是您请求的一部分。在这种情况下,你可以尝试,

$input   = $request->json()->all();

Just print_r($input) and see what you are getting.

只需 print_r($input) 看看你得到了什么。

If JSON object is not a part of your request, you missed passing $json to your function. This is a wild guess, though!

如果 JSON 对象不是您的请求的一部分,您就没有将 $json 传递给您的函数。不过,这是一个疯狂的猜测!

回答by mohammad gitipasand

you can use Response::json($value);

你可以使用 Response::json($value);