What you have is a JSON string:
var json = '["sgrdalal21"]';
You have to parse it as JSON to have an ordinary array.
Then you can access the string in the array:
var array, string;
try {
array = JSON.parse(json);
string = array[0];
} catch (e) {
// handle error
}
Remember that whenever you parse JSON strings which you are not sure that are valid (which is usually the case) then you will always have to wrap the JSON.parse()
call inside a try/catch
block or otherwise your app will crash on invalid JSON. I noticed that people rarely handle JSON.parse()
errors in the examples and then people are surprised that their servers are crashing and don't know why. It's because JSON.parse()
throws exceptions on bad input and has to be used with try/catch
to avoid crashing the entire app:
var array;
try {
array = JSON.parse(json);
} catch (e) {
// handle error
}
You can also use tryjson for that:
var array = tryjson.parse(json);
that will do that for you automatically. Now you can use:
var string = array && array[0];
and here the string
variable will be undefined
if the JSON was invalid or the array did not contain any elements, or will be equal to the inner string, just like in that first example with try/catch
above.