bubu
bubu

Reputation: 13

Javascript - Parsing JSON including int as Object

After several test and search, I can't find a way to navigate after parsing a JSON; here is the post-parsing result :

    Object {documentation: "https://geocoder.opencagedata.com/api", licenses: Array[2], rate: Object, results: Array[1], status: Object…}

documentation : "https://geocoder.opencagedata.com/api" licenses : Array[2] rate : Object results : Array[1] 0 : Object annotations : Object components : Object building : "C" city : "Bordeaux" country : "France" country_code : "fr" county : "Bordeaux" postcode : "33000" road : "Quai de Bacalan" state : "Aquitaine" suburb : "Bordeaux Maritime"

For example I can get the value of the response with the following code :

var locname = response.status.code;

But in the case there is a int as Object, like this :

var locname = response.results.0.formatted;

I have the following error :

Uncaught SyntaxError: Unexpected number

I try to escape the character, putting quote, etc but I couldn't find any solution.

Upvotes: 1

Views: 57

Answers (2)

Hans Yulian
Hans Yulian

Reputation: 1180

in javascript, an object is also accessible as array, so for example, you have an object like this:

var obj = {name: 'Hans Yulian', age: 21, message: 'Handsome'};
obj[0] = 'This is an number index';
obj['message'] = 'Too Handsome';

all the key is accepted as long as they aren't something that contain special characters (-+=! etc) and not started with number. in any case you have the field that don't satisfy this exception, then you have to access it in array-way. you can assign the value the same way as array, and also to get the content of that field.

in case you need to access something like

var locname = response.results.0.formatted;

Then the thing that you need is

var locname = response.results[0].formatted;

you can try make a html file with this content

<script>
    var obj = {name: 'Hans Yulian', age: 21, message: 'Handsome'};
    obj[0] = 'This is an number index';
    obj['message'] = 'Too Handsome';
    obj[1] = {};
    obj[1].name = 'Handsome';
    obj.handsome = [];
    obj.handsome[0] = {};
    obj.handsome[0].hansyulian = 'So Handsome';

    console.log(obj);
    console.log(obj[1].name);
    console.log(obj.handsome[0].hansyulian);
</script>

and try see the console(right click, inspect element, select console for google chrome) to understand what happens there

Upvotes: 1

Nick D
Nick D

Reputation: 1493

Since results is an array you must use the following syntax:

var locname = response.results[0].formatted;

Instead of

var locname = response.results.0.formatted;

Upvotes: 0

Related Questions