0

I have an array in Laravel controller like:

$succeeded[] = array('name' => $name,
                    'file' => $file
                        );
...
return $succeeded;

I use an ajax call for getting $succeeded, and I'll have a return string in js function composed of:

"[{"name":"sor.jpg","file":"399393.jpg"}]"

My question is how can I get "name" and "file" values from the string above?

Note: I didn't use any JSON object in controller, but returned just the array. However I wonder it is advantageous to use JSON object.

6
  • I presume that's supposed to be json? because if so, it's not valid json. And even if it was legitimate json, You don't access the json string directly. You decode the string to a native structure, and then you access the data like you would in any other data structure. Commented Sep 6, 2016 at 18:35
  • The returned value isn't a JSON object. I don't know whether it is advantageus to use JSON object in controller, though. Commented Sep 6, 2016 at 18:36
  • It is not a JSON object. Commented Sep 6, 2016 at 18:37
  • 1
    Well, that is a JSON encoded string. And, if you are returning that in an AJAX request, then you'll need to parse the JSON string into a javascript object. Commented Sep 6, 2016 at 18:39
  • Are the outmost wrapping quotes included in the string? If that's the case, you've to remove them before parsing. Commented Sep 6, 2016 at 18:42

1 Answer 1

0

You first need to parse the response text into a JSON array using the native JSON.parse, and then you can extract the values from the object in the parsed array using dot notation.

var respText = "[{\"name\":\"sor.jpg\",\"file\":\"399393.jpg\"}]";
var arr = JSON.parse(respText)[0];  // Careful - this will throw on invalid JSON
var name = arr.name;  // "sor.jpg"
var file = arr.file;  // "399393.jpg"
Sign up to request clarification or add additional context in comments.

4 Comments

Code-only answers are not useful. I understand what you are doing and why, but the code is a bit "compact", and would be unclear to a less experienced javacript coder. So - explain what you are doing at each step. You can ALSO point out a couple of alternatives - for example var arr = JSON.parse(respText); var obj = arr.shift(); var name = obj['name'];....
dot or bracket notation....
There are valid scenarios where you are required to use bracket notation, but the choice between dot notation and bracket notation for regular (alphabetic) strings is nothing more than a matter of style preference.
My point is this: You can point out the options. Bracket notation is very useful in many situations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.