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.

horse
  • 707
  • 4
  • 11
  • 30
  • 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. – Marc B Sep 06 '16 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. – horse Sep 06 '16 at 18:36
  • It is not a JSON object. – horse Sep 06 '16 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*. – random_user_name Sep 06 '16 at 18:39
  • Are the outmost wrapping quotes included in the string? If that's the case, you've to remove them before parsing. – Teemu Sep 06 '16 at 18:42
  • @Teemu Yes, string is that. – horse Sep 06 '16 at 18:43

1 Answers1

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"
  • 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'];`.... – random_user_name Sep 06 '16 at 18:37
  • `dot` *or bracket* notation.... – random_user_name Sep 06 '16 at 18:40
  • 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. –  Sep 06 '16 at 18:42
  • My point is this: You can point out the options. Bracket notation is very useful in many situations. – random_user_name Sep 06 '16 at 18:51