Navigating through a JSON API tree using jQuery - javascript

I'm trying to use a JSON api and retrieve some data. I'm still new to it though and I can't seem to figure out which value to use. My JSON API looks something like this:
[
{"lang":"english","visual":"<span>Text</span>","weight":0.92},
{"lang":"swedish","visual":"<span>Text</span>","weight":0.22},
//etc
]
and my jQuery is:
$.getJSON(url ,function(data) {
$.each(data.lang, function(i, item) {
dataName = item["visual"];
console.log(dataName);
});
});
but nothing is being logged. How do I navigate through a JSON tree? Thanks

data.lang is undefined. lang is a property of each object in the array of objects that data holds. Simply iterate the data array, each object will contain the visual property (as well as lang);
$.getJSON(url ,function(data) {
$.each(data, function() {
var lang = this["lang"];
var dataName = this["visual"];
console.log(dataName);
});
});

Related

JQuery: parsing ajax call versus imbedded str

I am confused because I have two functions, one using ajax to get the data and the other getting it from a string.
function loadMenuData() {
$.ajax({
url: "./shoulders.json",
success: function(data) {
dataObj = $.parseJSON(data);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
});
}
function loadMenuDataX() {
var str = '[{"id":"A","name":"Bart"},{"id":"B", "name":"Joe"},{"id":"C", "name":"Gomer"}]';
dataObj = $.parseJSON(str);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
I created the file shoulders.json buy pasting the str between the single quotes ' into the file. If I call loadMenuX, it fills in the <select></select> correctly. If I call loadMenu, it doesn't fill anything in.
I have tried JSON.parse instead of the above and get the same behavior.
I was unable to use $("#dropDownDest") and had to use $(document).find. Why?
Hitting the DOM each loop seems to be excessive. What would be a better way to do the ajax version THAT WOULD WORK and be better?
What would be a better way to do the ajax version THAT WOULD WORK and be better?
Because you're trying to get JSON file the better way is using jQuery.getJSON(), so you will be sure that the returned result is in json format :
$.getJSON( "./shoulders.json", function( json ) {
$.each(json, function( key, value) {
$("#dropDownDest").append('<option value="+value.id+">'+value.name+'</option>');
});
});
Hope this helps.

Deleting Row by Object ID in Parse

I don't know what is wrong with my code. I am trying to delete a specific row by the object ID in Parse. Right now, it's giving me a "error" in the console. I am not sure how to fix it. Thanks!
var rowId = Parse.Object.extend("Assignment");
var queryRemove = new Parse.Query(rowId);
var obj = $(elem).parent();
queryRemove.get("$(elem).parent().attr('id')", {
success: function(obj) {
console.log(obj + " got it");
obj.destroy({
success: function() {
console.log("Deleted!");
},
error: function () {
console.log("Deleted fail!");
}
});
},
error: function(obj ,error) {
console.log("error");
}
});
From the console log it is obvious that queryRemove.get is failing as you see error handler processed.
According to Parse Api reference you should be passing a string id to query.get(), so I suppose you've mistaken in the parameter. JQuery should be evaluated and .get should receive id of an element not a string "$(elem).parent().attr('id')" which is obviously not a good id
queryRemove.get($(elem).parent().attr('id'), {
Also doesn't look like you can delete an item with .get()... Have analysed parse.com api before using it?

How can I convert JSON format file to JSON object?

I use a dojo request.get to read a txt file in JSON format, but can't convert it to JSON object.
The "datagrid.txt" stored some data as:
[
{"col1":"val1", "col2":"val2", "col3":"val3"},
{"col1":"val1", "col2":"val2", "col3":"val3"},
{"col1":"val1", "col2":"val2", "col3":"val3"}
]
The requesting client code is as:
require(['dojo/_base/lang', 'dojox/grid/DataGrid', 'dojo/data/ItemFileWriteStore', 'dojo/dom', 'dojo/request', 'dojo/domReady!'],
function(lang, DataGrid, ItemFileWriteStore, dom, request){
request.get("datagrid.txt",{
// Parse data from JSON to a JavaScript object
handleAs: "json"
}
).then(
function(text){
var datalist = JSON.stringify(text);
for(var i = 0, l = 16; i < l; i++){
console.log( datalist[i] );
}
});
The console.log displays things in string(such as "[","{"), not what as I expected an array({"col1":"val1", "col2":"val2", "col3":"val3"}), which I could used to populate a dojo datagrid data store.
Dojo can handle the JSON format on its own. Official docs
I think your Problem lies in the way you're writing your datagrid.txt and the style you try to read the data later.
Here's my solution:
require(['dojo/_base/lang', 'dojox/grid/DataGrid', 'dojo/data/ItemFileWriteStore',
'dojo/dom', 'dojo/request', 'dojo/domReady!'],
function(lang, DataGrid, ItemFileWriteStore, dom, request){
request.get("datagrid.txt",{
// Parse data from JSON to a JavaScript object
handleAs: "json"
}
).then(
function(text){
var datalist = [];
dojo.forEach(text,function(thisText,i){
//add each single Object from the datagrid.txt to datagrid-array
datalist.push(thisText);
//alert the newly added item in datagrid
console.log(datalist);
});
});
I think this should fix your Problem.
Regards, Miriam

Populate input field with value from json

In my rails app, i need to populate 1 field with value that came in json, which was returned by clicking on link. Is there any tutorial on how to correctly use ajax to do such thing?
Here is my plan how to do this:
1.Send get request to my json appname/controller/action.json
2.parse this json on client side
3.set value of field with parsed json
I am assuming your json string is like that
[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]
use the $.getJSON method:
$.getJSON('/appname/controller/action.json', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
Assuming data is the JSON object, you could use this inside the $.getJSON callback:
var $inputs = $('form input');
$.each(data, function(key, value) {
$inputs.filter(function() {
return key == this.name;
}).val(value);
});
second way
eg: JS fiddle

How can I convert this Json array to a format readable by JQuery?

Bit of a vague question, but I'm unsure how I can this to work. Firebug says the Json object (array?) from my ajax request looks like:
{
"jsonResult":
"[
{\"OrderInList\":1},
{\"OrderInList\":2}
]"
}
This is retrieved through through a $.getJSON ajax request:
$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, testData, function (jsonResult) {
$('#orderInList option').remove();
var map = {
"TestKey1": "TestValue1",
"TestKey2": "TestValue2"
};
$.each(jsonResult, function (key, value) {
$("#orderInList").append($("<option value=" + key + ">" + value + "</option>")
);
});
If I replace $.each(jsonResult) with $.each(map) the select list populates correctly. Otherwise my select list just says 'undefined'.
I serialize the Json in this Action in my MVC Controller:
public JsonResult GetOrderSelectList(int parentCategoryId)
{
var result = Session
.QueryOver<Category>()
.Where(x => x.Parent.Id == parentCategoryId)
.OrderBy(x => x.OrderInList).Asc
.List();
var toSerialize =
result.Select(r => new {r.OrderInList});
var jsonResult = JsonConvert.SerializeObject(toSerialize);
return Json(new
{ jsonResult,
}, JsonRequestBehavior.AllowGet);
}
So I think the problem might be the format of Json the Action is responding with? Any help appreciated!
Edit for answer
Both of the answers below helped me. I couldn't seem to strongly type the variable jsonResult so thanks #JBabey for pointing out my error in reading the json property, and suggesting function (key, value) in the $.each statement.
Thanks #Darin Dimitrov for helping sort my controller out!
Your controller action is wrong. You are manually JSON serializing inside it and then returning this as a JSON result thus ending up with a double JSON serialization. You could directly return the array and leave the JSON serialization plumbing to the ASP.NET MVC framework:
public ActionResult GetOrderSelectList(int parentCategoryId)
{
var result = Session
.QueryOver<Category>()
.Where(x => x.Parent.Id == parentCategoryId)
.OrderBy(x => x.OrderInList)
.Asc
.List();
return Json(result, JsonRequestBehavior.AllowGet);
}
and then:
$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, testData, function (jsonResult) {
$('#orderInList option').remove();
$.each(jsonResult, function () {
$('#orderInList').append(
$("<option value=" + this.Id + ">" + this.Value + "</option>")
);
});
});
Notice that I am using this.Id and this.Value here. This assumes that the JSON result looks like this:
[{"Id": 1, "Value": "some value"}, {"Id": 2, "Value": "some other value"}]
You will have to adapt those property names based on your actual Category model.
You are confusing a property of your data returned by your ajax with the data itself. $.each will work fine if you correct this.
Your data returned looks like this:
{
"jsonResult": "[
{\"OrderInList\":1},
{\"OrderInList\":2}
]"
}
Which means that is the object passed to your success function. Call it data instead of jsonResult.
function (data) {
...
$.each(data.jsonResult, function (key, value) {
...
});
});
Also, your array is coming through as a string, so you may need to parse it before $.each will be able to iterate it.

Categories