简体   繁体   English

如何在 Laravel 中解码 JSON 对象

[英]How to Decode JSON object in Laravel

I want to decode gallery array JSON objects in Laravel 5.1.我想在 Laravel 5.1 中解码画廊数组 JSON 对象。 my JSON is:我的 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}]

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}]

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.我不太确定您的程序流程,但是当您向 store 函数注入请求依赖项时,我假设 JSON 对象是您请求的一部分。 In that case, you can try,在这种情况下,你可以尝试,

$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.如果 JSON 对象不是您的请求的一部分,您就没有将 $json 传递给您的函数。 This is a wild guess, though!不过,这是一个疯狂的猜测!

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

Just dropping by for having the same issue of trying to get the json formatted response (Laravel 8.8.0).只是因为遇到同样的问题,试图获得 json 格式的响应(Laravel 8.8.0)。 The way I was able to get it working was using:我能够让它工作的方式是使用:

$jsonFormattedResult = json_decode ($response->content(), true);

Hope it helps someone out.希望它可以帮助某人。 ( '-')/ ('-')/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM