Vishnu
Vishnu

Reputation: 751

JSON data to javascript Array Android browser .length gives wrong value

My JSON DATA from URL:

[ { "url": "http://google.com" }, { "url":"http://yahoo.com" } ]

This will bring a list of URLS

jsOnData.push(xhr.response);

jsOnData.length will return 1 jsOnData[0][0].url will return first url jsOnData[0].length will return 2 but in Android 4.4.4 Default browser it is abnormal value and it is not working as expected. In Desktop browser and Mobile Chrome, Opera, Firefox it is working as expected. But Android browser, UC WEB, Dolphin it is not working and also retuning same abnormal value.

Abnormal value: 101 (on Android browser, UC WEB & Dolphin)

Which is the best way to get list of urls from JSON file and Parse it to normal JavaScript Array?

Upvotes: 0

Views: 483

Answers (2)

Jason Cust
Jason Cust

Reputation: 10909

I think you have a misunderstanding of what JSON is. JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. What you want is colloquially referred to as a POJO or Plain Old Javascript Object. They are different.

It seems like whatever you are using to make the HTTP request is auto parsing the JSON response into a POJO on some browsers and not on others.

var json = '[{"url":"http://google.com"},{"url":"http://yahoo.com"}]';
json.length // 56 (this is the character count since json is a string)
var obj = JSON.parse(json);
obj.length // 2 (since there are two items in the array
obj[0].url // 'http://google.com'

UPDATE: after discussion with OP, his issue was lack of support for responseType in his XMLHttpRequest handler (it's a level 2 enhancement where as the browsers in question only support level 1). Added the following check to see if the response was auto-parsed to an object and if not do it manually:

var obj = typeof xhr.response === 'string' ? JSON.parse(xhr.response) : xhr.response;

Upvotes: 2

Eugene Glova
Eugene Glova

Reputation: 1553

Use concat instead of push, because you add one array to another

Upvotes: -1

Related Questions