However, it is not always obvious that a piece of data your application is trying to use may be of type JSON, or be correctly sanitised.
Now let’s use the following value for
If we ran this test, we would get back
"Andrew" in our return.
The problem with this sort of thing is that you should always write software for when things could break. But how do we know what could break? An easy way to find out, is to mess with the
jsonString test value.
What happens if we call the function with some other data type. A blank value, or something else perhaps?
Calling the function without passing in any value will give us the following error:
The same would be true if we received some arbitrary string, such as
We could just wrap the entire contents of the function in a
Or we could do something a bit cleaner:
The second option checks to make sure the JSON was parsed and that there is a key with the value
name before attempting to return it. As an added step, a blank string is returned if all else fails. This makes sure that our application always gets a valid value back.