6

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

{ "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:

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

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

[{'name': "XCB808tvXNpqXKqekA2HlkJ8H.jpg",'size':5112},{'name': "s6kA6B0e5m1sdSAjPXqNwtiy4.jpg", 'size': 13135}] 
8
  • Kindly place your full code Commented Mar 12, 2016 at 9:45
  • gallery in not a JSON object, but list of JSON objects, so first divide them - you can use explode() for that. Commented Mar 12, 2016 at 9:48
  • what should I do explode ? Commented Mar 12, 2016 at 9:54
  • What is the result of dd( $request['gallery'] ) ? Commented Mar 12, 2016 at 10:06
  • [{'name': "XCB808tvXNpqXKqekA2HlkJ8H.jpg",'size':5112},{'name': "s6kA6B0e5m1sdSAjPXqNwtiy4.jpg", 'size': 13135}] Commented Mar 12, 2016 at 10:07

4 Answers 4

6

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

Replace the single quotes around property names with double quotes:

[{"name": "XCB808tvXNpqXKqekA2HlkJ8H.jpg","size":5112},{"name": "s6kA6B0e5m1sdSAjPXqNwtiy4.jpg", "size": 13135}] 
Sign up to request clarification or add additional context in comments.

Comments

1

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,

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

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

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

Comments

1

Just dropping by for having the same issue of trying to get the json formatted response (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. ( '-')/

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.