Reputation: 7561
I am parsing JSON and trying to access one of its fields, which is an array.
const myObj: MyObj = JSON.parse(myJson);
console.log(myObj.myArray); //SyntaxError: Unexpected end of JSON input
console.log(myObj.myArray == 'undefined'); //SyntaxError: Unexpected end of JSON input
console.log(myObj.myArray.length); //TypeError: Cannot read property 'length' of undefined
console.log(myObj.myArray !== null); //true
I have no problem iterating through my array and doing what I need with the data. But I need to check to make sure the myArray
field is valid being iterating through it. When I try to do this, I get an error as shown above.
I am very very confused. Can anyone explain to me what is going on and how to fix it?
Upvotes: 1
Views: 106
Reputation: 27202
You can check few things to verify that passed input is valid or not.
if(myObj.myArray) { }
[]
Hence, when trying to parse []
it returns ""
and giving the below error.
SyntaxError: Unexpected end of JSON input
var myObj = JSON.parse([]);
console.log(myObj.myArray);
Upvotes: 1
Reputation: 10366
You can use the in
operator to check whether a property is specified in an object prototype chain:
const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);
console.log('myArray' in myObj); // false
console.log('a' in myObj); // true
Alternatively, you can check whether the field is not undefined
(if it is, it does not exist in the object returned by JSON.parse
), and the safest way of doing this is by using the typeof
operator:
const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);
console.log(typeof myObj.myArray !== 'undefined'); // false
console.log(typeof myObj.a !== 'undefined'); // true
A direct comparison against undefined
(e.g., myObj.myArray !== undefined
) should be avoided because undefined
can be overridden or shadowed.
EDIT: As @OliveNi pointed out, the usage of the in
operator is dangerous because it goes through the entire prototype chain. For a safer check (as an alternative to undefined
check), you can use hasOwnProperty
as exemplified in his answer.
Upvotes: 1
Reputation: 42627
If you are concerned about existence, you can simply check
if (myObj.myArray) {
If you want to confirm existence and confirm it's an array
if (myObj.myArray && Array.isArray(myObj.myArray) {
Upvotes: 1
Reputation: 2664
Be careful while using in
, as it searches the entire prototype chain.
const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);
console.log('constructor' in myObj); // true (BAD)
Instead, try using .hasOwnProperty()
, like so:
const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);
console.log(myObj.hasOwnProperty("a")); // true
console.log(myObj.hasOwnProperty("constructor")); // false
Upvotes: 1