Can't access nested json elements with javascript - javascript

I'm really stuck on how to access nested elements of a json response that I'm getting from my api. I validated the json and it shows as valid.
For instance, how do I access the numFound attribute? Here's my code that is not working:
$.ajax({
url: "/api/SearchAPI/infopop?id=" + songID,
datatype:"json",
method: "get"
}).done(function (data) {
var obj = JSON.parse(data);
alert(obj); /* This displays the entire json response
alert(obj.response.numFound) /* This does not work
alert(data.response.numFound) /* This does not work
Here's the response I'm trying to access
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"*:*",
"indent":"off",
"fl":"Name,Description,Keywords,ISRC,Instruments,Lyrics,Bpm,Vocal,Tempo,Key,TV_Genres,Music_Genres,length\r\n,Writers,profileImagePath\r\n,Publishers\r\n,songImagePath\r\n,Band_Styles",
"start":"0",
"callback":"?\r\n",
"fq":[
"id:00106c8c-7e21-4e75-80da-cdff8e6d3d44",
"publicflag:1",
"pubname:komposed"
],
"rows":"10",
"version":"2.2",
"wt":"json"
}
},
"response":{
"numFound":1,
"start":0,
"docs":[
{
"profileImagePath":[
"https://komposed.blob.core.windows.net/jrock-1873564a-d409-4370-80d8-23dc97114f18/songimage/f557110f-4ad3-4353-a1b3-3ba70d52e8f0?sv=2014-02-14&sr=b&sig=Q3ywrwEa6URp%2FPCvK0Ngesza8PBhMEmE5ONeKhw8vE4%3D&st=2016-06-16T16:49:45Z&se=2066-06-16T16:54:45Z&sp=r&rsct=application%2Foctet-stream&rscd=attachment%3B%20filename%3Dredneck.jpeg"
],
"songImagePath":[
"https://komposed.blob.core.windows.net/jrock-1873564a-d409-4370-80d8-23dc97114f18/songimage/f0c00dcd-69f9-42af-b236-4a53f0d78e76?sv=2014-02-14&sr=b&sig=oF0STMDddyuJiNZO%2BE78sYtbboC4ic%2Fl4bR5ESBFouE%3D&st=2016-06-16T16:48:59Z&se=2066-06-16T16:53:59Z&sp=r&rsct=application%2Foctet-stream&rscd=attachment%3B%20filename%3DTENSION%20LAST%20MAN.jpg"
],
"Name":[
"Bottle Service Tension"
],
"Description":[
"Cool crime scene track with a chill night club vibe"
],
"Bpm":[
90
],
"Vocal":[
"Acapella"
],
"Tempo":[
"Fast"
],
"Writers":[
"Justin Sirota|100.00|"
],
"Keywords":[
"club, crime, investigation, cool, lounge, pulse"
],
"TV_Genres":[
"Tension"
]
}
]
}
}

Just use obj.numFound. response is your data argument.
$.ajax({
...
}).done(function (response) {
alert(response.numFound)
...
Also, since you're telling jQuery (assuming this based on the code) that the response is of JSON type via datatype:"json", you don't need to do JSON.parse on it.

Turns out the issue was in my API. I was returning json as a string instead of an object. Once I did that, javascript was able to reference the json elements. Thanks for trying to help!

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.

AngularJS $http patch request not sending data

The data is being passed to the replyMessage as the console log is showing the correct data, however, the API isn't receiving this data. Input is empty?
replyMessage: function(data) {
console.log(data);
return $http.patch('/api/email/inbox/0', data);
}
Can you see any issues with this or any things to look at?
Are you formatting patch correctly?
It needs to be a JSON.stringify(data) Array.
With data being formatted like so:
[
{
"op" : "replace",
"path" : "/Name", // <-- this is what field you're editing
"value" : "John Doe"
}
]
Also you might need your contentType to be application/json-patch+json;

How do I extract a specific value from a JSON returned object with javascript?

I'm doing the codecademy javascript API tutorial using calls to the Sunlight Foundations API. i have completed the full codecacemy javascript course, and may be missing soemthign simple.
I would like to extract the number of results from the returned JSON Object, which is currently being displayed in HTML thanks to jquery.
here is a sample of the returned object:
{
"num_found": 347,
"results": [
{
"speaker_state": "NC",
"speaker_first": "Virginia",
"congress": 111,
"title": "CULTIVATING AMERICAN ENERGY RESOURCES",
"origin_url": "http://origin.www.gpo.gov/fdsys/pkg/CREC-2009-07-30/html/CREC-2009-07-30-pt1-PgH9197.htm",
"number": 117,
"pages": "H9197-H9203",
"volume": 155,
"chamber": "House",
"session": 1,
"speaking": [
"Well, I think that this is a great segue to talk about the other subject that we wanted to talk about tonight, which is health care, and what is happening with the health care debate."
],
"capitolwords_url": "http://capitolwords.org/date/2009/07/30/H9197_cultivating-american-energy-resources/",
"speaker_party": "R",
"date": "2009-07-30",
"bills": null,
"bioguide_id": "F000450",
"order": 14,
"speaker_last": "Foxx",
"speaker_raw": "ms. foxx"
},
...
]
}
Here is the last statement that shows the results:
var query_params = { apikey: 'f6ab5f2e4f69444b9f2c0a44d9a5223d',
phrase: word
};
var endpoint = 'http://capitolwords.org/api/text.json'
var options = {
data: query_params,
type: 'GET',
dataType: 'jsonp'
};
var request = jQuery.ajax(endpoint, options)
.done(showResponse);
If the last line above returns the object, how do I chain a method onto .done() which will extract for example, "num_found"?
That's the hint provided is to chain a method, but I don't quite get this. Thanks for any help.
You can execute a function after the AJAX request has (successfully) finished by adding the "success" option:
var query_params = {
apikey: 'f6ab5f2e4f69444b9f2c0a44d9a5223d',
phrase: word
};
$.ajax({
url: 'http://capitolwords.org/api/text.json',
data: query_params,
type: 'GET',
dataType: 'jsonp',
success: showResponse
});
function showResponse(response) {
alert(response.num_found);
}
It will be passed the response from the server as an object, because jQuery does all the complicated JSONP work for you. This example will execute the function showResponse and and alert the value of num_found.
This might also help you: http://learn.jquery.com/ajax/working-with-jsonp/
Not sure but I think this is what you want:
.done(function(data){
var myVar = .....
showResponse(myVar);
});

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

twitter typeahead 0.9.3 remote return URL and json object

in bootstrap 2, I used the following code to post a json object,
$('#typeahead').typeahead({
source: function (query, process) {
var URL = 'http://localhost:8080/autocomplete/search/';
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return $.getJSON(URL,
{ query: JSON.stringify(query)},
function (data) {
return process(data);
});
}
});
Now in twitter tyeahead 0.9.3 they have done away with the source concept and moved to a remote concept, but unfortunately I do no know how to work with it.
$(".typeahead").typeahead({
remote : {
url: 'http://localhost:8080/autocomplete/search/',
replace: function(uri, query) {
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return uri + JSON.stringify(query);
},
filter: function(response) {
return response.matches;
}
return process(resultList);
}
}
Unfortunately it doesn't work, how do I just post the JSON object rather than appending it to the string? Thanks.
In your original code you use $.getJSON. This will send a request (and expects json as result) to: http://localhost:8080/autocomplete/search/?query=%7B%22t%3AjsonStringField%22%3A%7B%22name%22%3A%22model%22%2C%22value%22%3A%22fusion%22%7D%2C%22t%3AjsonStringFilter%22%3A%5B%7B%22name%22%3A%22year%22%2C%22value%22%3A%222009%22%7D%2C%7B%22name%22%3A%22make%22%2C%22value%22%3A%22ford%22%7D%5D%7D
To do the same for Twitter's Typeahead call your replace function of your remote data should return a valid url. In your function the ?query= part of the url is missing.
You will have to set: url: 'http://localhost:8080/autocomplete/search/?query=',
You also will have to urlencode you json input maybe.
Note: you will not need the line return process(resultList); You will have to use the filter function to convert your json results to valid data:
The individual units that compose datasets are called datums. The
canonical form of a datum is an object with a value property and a
tokens property.
you could use templates to style your dropdown results, see: http://twitter.github.io/typeahead.js/examples/
By default, the dropdown menu created by typeahead.js is going to look
ugly and you'll want to style it to ensure it fits into the theme of
your web page.
You will need the additional CSS from https://github.com/jharding/typeahead.js-bootstrap.css to style the default dropdown for Bootstrap.

Categories

Resources