Reputation: 317
I am having some problems to receive a JSON response. This is the POST response:
{
"id": xxxxx,
"name": "xxx",
"description": null,
"latitude": null,
"longitude": null,
"created_at": "2015-11-28T12:52:07Z",
"elevation": null,
"last_entry_id": null,
"ranking": 15,
"metadata": null,
"username": "xxxxxxxxxx",
"tags": [],
"api_keys": [
{
"api_key": "XXXXXXXXXXXXX",
"write_flag": true
},
{
"api_key": "XXXXXXXXXXXXX",
"write_flag": false
}
]
}
And this is my function in jQuery:
function Thingspeak(){
var API = $('#API_Key').val();
$.ajax({
type: "POST",
url: "https://thingspeak.com/channels.json",
data: {api_key: API, name: 'test', field1: 'tm', field2: 'hm', field3: 'bn'},
success: function(data) {
var id = data.id;
var API_r = data.api_keys[0][0];
var API_w = data.api_keys[1][0];
console.log(id+": "+API_r+" "+API_w)
}
});
}
I receive the channel_id perfectly, but for the api_keys, I have tried to looking for some ways to receive but without any luck. I think is a very simple question, but I am totally stuck with this.
Upvotes: 0
Views: 70
Reputation: 144
var API_r = data.api_keys[0].api_key;
var API_w = data.api_keys[1].api_key;
Upvotes: 0
Reputation: 54841
data.api_keys
is an array of objects.
Sure, you can access first element of array
with [0]
.
But if you print it:
console.log( data.api_keys[0] );
you will see that data.api_keys[0]
is an object with 2 props - api_key
and write_flag
. So proper code should be:
console.log( data.api_keys[0].api_key );
// or
console.log( data.api_keys[0]["api_key"] );
Upvotes: 1