jQuery: Get JSON error - javascript

I'm trying to get certain elements from a JSON file but I'm just not able to do so, I've tried different ways, this is the JSON file:
// data.json
{
"stuff": [
{
"userId": 1,
"date": "19 Oct 2014",
"content": "#New Hello on g.co/ABC",
"entities": {
"hashtags": ["#New"],
"urls": ["g.co/ABC"]
}
}
],
"user": {
"avatar": "/assets/avatar.jpg",
"name": "Daniel"
}
}
Now my jQuery code is:
$(document).ready(function(){
$.getJSON('data.json', function(data) {
//console.log(data);
$.each(data,function(i,item){
console.log(item.stuff.content); // I want to print 'content'
});
});
});
And all I get is an Uncaught error type:
What am I doing wrong? Thanks in advance

stuff is an array of object.
To access item of an array you have to access it via index
like this
console.log(data.stuff[0].content);
JSFIDDLE
May be you are iterating an object instead of array of object
If data is an object then try like this
$.each(data.stuff,function(i,item){
console.log(item.content);
});
JSFIDDLE

This should work:
$.getJSON('data.json', function(data) {
console.log(data['stuff'][0]['content']);
}
It is getting the stuff element of the JSON object then the first element of that pair, since the pair of key "stuff" is an array of JSON Objects. Then from that last JSON object, its grabbing content.

You json data is not an array. so you don't need to use each. But stuff is an array so take it's specific index or loop through it.
$(document).ready(function(){
$.getJSON('data.json', function(data) {
console.log(data.stuff[0].content);
//or loop through like
//$.each(data.stuff,function(i,item){
// console.log(item.content);
//});
});
});

Related

finding nested object value in java script

JSON file from URL
{
"1": [
{
"actions": ["OUTPUT:2" ],
"idle_timeout": 0,
"cookie": 0,
"packet_count": 2,
"hard_timeout": 0
}
}
JavaScript
function myFunction() {
//alert("INTo function");
$.ajax({
url: "http://127.0.0.1:3000/flow",
cache: false,
success: function(data) {
$("#flow").append(data["1"].actions.OUTPUT[i]);
$("#flow").append(data["1"].idle_timeout);
$("#flow").append(data["1"].cookie);
$("#flow").append(data["1"].packet_count);
$("#flow").append(data["1"].hard_timeout);
}
});
}
This is the JavaScript code which I have used it, to find values of the object inside the nested JSON response coming from a URL.
Your sample does not look like valid json. Since the value of "1" is an array, you should try to access it via the index. e.g.$("#flow").append(data["1"][0].idle_timeout)
The code used to find the values inside the nested JSON object is actually incorrect.
You must use data["1"][0].actions[0].OUTPUT to retrieve the value 2.

Not able to set text in input field from json response

I have a form in which I have to fill data after I have got a json object from httpGet in javascript.
$("#getDetails").click(function() {
$.get("/servlet",{
mID : 5
})
.done(function(data) {
$("#input1").val(data["some key"]);
$("#input2").val(data.name);
$("#input3").val("directvalue");
});
});
In the above 3 fields, only input3 gets filled with "directvalue".
Is there some problem in accessing json object or in setting value of input fields.
Note: the json object contains keys with spaces like "some key":"some value"
edit:
When I tried Object.keys(data)[index] to access the object field, I got Uncaught TypeError: Object.keys called on non-object
Try This
$("#getDetails").click(function () {
$.get("/servlet", {
mID: 5 })
.success(function (data) {
$("#input1").val(data.d.somekey);
$("#input2").val(data.d.name);
$("#input3").val("directvalue");
});
});
In the comments, you say it's returning this object:
{
"Name": "my name",
"my address": "23,round street",
"Description": "PM Speech at Red Fort on Indep Day 2014"
}
Try:
$("#input2").val(data.Name);
When I did console.out(data), it was printing a json object.
But when I tried Object.keys(data)[index] to access the object field, I got Uncaught TypeError: Object.keys called on non-object.
This means that dataitself was not a json object.
So I got a hint that server was giving a string in which json object was written. I had to simply parse the json object from the data string.
Following is the working code:
$("#getDetails").click(function() {
$.get("/servlet",{
mID : 5
})
.done(function(data) {
var dataObj=JSON.parse(data);
$("#input1").val(dataObj["some key"]);
$("#input2").val(dataObj.name);
});
});

Parsed elements coming up as undefined

I'm trying to parse the following JSON:
{
"customers": [
{ "name":"joe" , "cars":[
{"name":"honda","visits":[
{"date":"01/30/14","Id":"201"},
{"date":"01/30/14","Id":"201"},
{"date":"02/12/14","Id":"109"}
]},
{"name":"Nissan","visits":[
{"date":"01/30/14","Id":"201"},
{"date":"02/12/14","Id":"109"}
]}
]},
{ "name":"bob" , "cars":[
{"name":"escalade","visits":[
{"date":"01/05/14","Id":"301"},
{"date":"01/18/14","Id":"551"}
]},
{"name":"corvette","visits":[
{"date":"01/05/14","Id":"301"},
{"date":"01/18/14","Id":"551"}
]}
]}
]
}
Using the following jQuery script:
$("document").ready(function(){
$.getJSON("data1.json", function(json) {
console.log(json); // this will show the info it in firebug console
$.each(json.customers,function(customer){
console.log(customer.name);
console.log(customer.cars);
});
});
});
The JSON is coming through in the console but the fields I'm trying to parse are coming up as undefined. Can anyone ell me what I'm doing wrong?
I think the issue here is your usage of $.each, your callback function will receive the index as the first argument and the value as the second argument and it looks like you are expecting the first argument to be the value. So in your current code customer will be an index (0, 1, etc.) rather than the object from your JSON.
Try changing your $.each call to the following:
$.each(json.customers, function(index, customer) {
console.log(customer.name);
console.log(customer.cars);
});

Facebook Feed - JS SDK

I am trying to create a user's feed on my page using Facebook JS SDK but I am having issues accessing the values of nested objects.
This is my code:
FB.api('/me/feed', function(response) {
alert(response.data);
});
The alert here will return [object Object]
The data object is this:
{
"data": [
{
"message": "Some message",
"id": "some ID",
"created_time": "2014-01-05T22:46:10+0000"
}
],
"paging": {
"previous": "Link",
"next": "Link"
}
}
I need to access the message part of the object but I don't know how.
Simply access the properties directly
FB.api('/me/feed', function(response) {
alert(response.data.message);
});
I had to use JSON after all
FB.api('/me/feed',{limit:10}, function(response){
var jsonText = JSON.stringify(response.data,["picture"]);
alert(jsonText);
});
This will return an array with all the values of 'picture'
This is the example output
[{"picture":"https://fbcdn-photos-d-a.akamaihd.net"},
{"picture":"https://fbcdn-photos-g-a.akamaihd.net"},
{"picture":"https://fbexternal-a.akamaihd.net"},{},
{"picture":"https://fbcdn-profile-a.akamaihd.net"}]
It looks likedata is an array with a single element, so to get message, you will want to use response.data[0].message

Get Data from JSON String

I'm unable to successfully get data from the JSON string below. Using JavaScript, I'm able to alert the full string [ alert(data); ] but I'm unable to get only the first name.
Can someone please help?
var data = {
"name": [
"Enid Norgard",
"Cassie Durrett",
"Josephine Ervin"
],
"email": [
"TheWoozyGamer#gmail.com",
"TheHabitualGamer#gmail.com",
"TheUptightGamer#gmail.com"
],
"role": [
"Gamer",
"Team Leader",
"Player"
],
"emp_id": [
"50",
"408",
"520"
],
"id": [
"234",
"444",
"235"
]
}
Looks like you have a string(because when you use alert the complete text is shown, if it was a object then [Object object] would have shown), first you need to parse it using JSON.parse()
var t = JSON.parse(data)
alert(t.name[0])
Note: Old browsers like IE8 which does not have native support for JSON you have to add a library like json2 to add JSON support
use the following code
alert(data.name[0]);
//sample code
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
Most browsers support JSON.parse(), hope this will help you for detail see link.
With data.name[0] you will get the name Enid Norgard
Similar to that use
data.name[index]
while index is the position of the name in the innerarray.
If you want only the names array use:
alert(data.name)
try this to loop through all elements
for(x in data)
{
for(y in data[x])
{
alert(data[x][y]);
}
}

Categories

Resources