JSON to usable array javascript - json

I'm trying to convert my JSON code to a usable array in javascript/jquery.
I have the following JSON code arriving via ajax:
[{"id":"9","firstname":"Greg","surname":"Bril","position":"0","busy":"0","disabled":"0"},{"id":"14","firstname":"Nai","surname":"Brooks","position":"1","busy":"0","disabled":"0"},{"id":"17","firstname":"Margaret","surname":"Grey","position":"1","busy":"0","disabled":"0"},{"id":"1","firstname":"Cameron","surname":"Grover","position":"0","busy":"0","disabled":"0"},{"id":"2","firstname":"Sarah","surname":"Grover","position":"0","busy":"0","disabled":"0"},{"id":"3","firstname":"Margaret","surname":"Hynes","position":"0","busy":"0","disabled":"0"},{"id":"4","firstname":"Stephen","surname":"Hynes","position":"0","busy":"0","disabled":"0"},{"id":"11","firstname":"Ben","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"15","firstname":"Elizabeth","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"10","firstname":"Grant","surname":"Mills","position":"0","busy":"0","disabled":"0"},{"id":"16","firstname":"John","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"13","firstname":"Lucinda","surname":"Ower","position":"1","busy":"0","disabled":"0"},{"id":"12","firstname":"Karina","surname":"Scott","position":"1","busy":"0","disabled":"0"}]
It is created and intepreted using:
$.getJSON( "tc_search1.php", {
leave: $("input#leave").val(),
end: $("input#end").val(),
override: $("#tc_override").is(":checked"),
tc_id: $("#tc_id").val()
}, function(data) {
//i cant get this part to work
});
I can't seem to manage to get the function on success to work. I tried the $.each method on jquery documentation website, but I can't get it right. Can anyone help?

The getJSON method will automatically parse the JSON string into a Javascript object.
The data parameter in your success callback function will be an array of objects. For example, the expression data[0].firstname will return "Greg".

Related

Having trouble retrieving JSON from res

I'm using node, express, and mongoose.
I have a function that performs a search in a database and sends the response in a JSON format with:
res.jsonp(search_result);
This displays the correctly returned result in the browser as a JSON object. My question is, how do I get that JSON object?
I've tried returning search_result but that gives me null (possibly because asynchronous). I'd also like to not edit the current function (it was written by someone else). I'm calling the function and getting a screen full of JSON, which is what res.jsonp is supposed to do.
Thanks in advance.
Just make a new function that takes this JSON as parameter and place it inside the old one. Example:
// Old function
app.get('/', function(req,res){
// recieve json
json_object = .....
// Get json to your function
processJson(json_object);
// Old function stuff
.
.
.
});
function processJson(json_object) {
// Here you'll have the existing object and can process it
json_object...
}

How to get a list via POST in Restangular?

Consider a REST URL like /api/users/findByCriteria which receives POSTed JSON that contains details of the criteria, and outputs a list of Users.
How would one call this with Restangular so that its results are similar to Restangulars getList()?
Restangular.all('users').post("findByCriteria", crit)... might work, but I don't know how to have Restangular recognize that the result will be a list of Users
Restangular.all('users').getListFromPOST("findByCriteria", crit)... would be nice to be able to do, but it doesn't exist.
Doing a GET instead of a POST isn't an option, because the criteria is complex.
Well,
I experience same problem and I workaround it with plain function, which return a plain array of objects. but it will remove all Restangular helper functions. So, you cant use it.
Code snippet:
Restangular.one('client').post('list',JSON.stringify({
offset: offset,
length: length
})).then(
function(data) {
$scope.clients = data.plain();
},
function(data) {
//error handling
}
);
You can get a POST to return a properly restangularized collection by setting a custom handler for OnElemRestangularized in a config block. This handler is called after the object has been Restangularized. isCollection is passed in to show if the obect was treated as a collection or single element. In the code below, if the object is an array, but was not treated as collection, it is restangularized again, as a collection. This adds all the restangular handlers to each element in the array.
let onElemR = (changedElem, isCollection, route, Restangular: restangular.IService) => {
if (Array.isArray(changedElem) && !isCollection ) {
return Restangular.restangularizeCollection(null, changedElem, changedElem.route);
}
return changedElem;
};
RestangularProvider.setOnElemRestangularized(onElemR);

Parse Json to use in a dojo widget?

I am newbie to dojo and json. I am trying to Query the server to get data as json and parse the result and use html template in a widget to display.
To test it I tried this.
require(["dojo/request", "dojo/dom", "dojo/dom-construct","dojo/_base/array", "my/widgets/", "dojo/domReady!"],
function(request, dom,domConst, arrayUtil, support){
// Load up our authors
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function(LinksMap){
// Get a reference to our container
arrayUtil.forEach(LinksMap, function(List){
// Create our widget and place it
console.debug(LinksMap);
//var widget = new support(author).placeAt(authorContainer);
Not sure if I am doing it right. Is there anything I am misssing. I am following the example as provided here and building on it.
I think from the comments on your post you want to modified the deferred handling function to be
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function(jsonResults){
console.log(jsonResults.Result)
});
The json you posted is an object with a property Result. The Result property contains an array of objects. Those objects then contain a property LinksMap which holds another object.

calling JSON webservice & using html

I've been using XML a lot lately but now I'm practicing with some JSON.
What I am trying to do is make a button and text box - so the user can type in a zip code and it will get the info for that zip code...
Using JSON from geonames.org
It's frustrating me trying to figure this out, I've found it easy when I was making my own files with XML but now I am trying to use an actual website and JSON.
Please show me how to do this! Would appreciate it! Thanks.
First of all HTML cannot process a json response from a server. You can send a get or post in json format to a server and get a json response back but you need something other than HTML to process that JSON message. Browsers can format and display XML but not JSON (they just display it as a string). The easiest way to do that in a browser is use JavaScript. For this I would recommend using the jquery library.
http://jquery.com
Here's an example of some jquery I used recently to process a returned JSON string.
$(document).ready(function() {
$(".img a").on("click", function(event) {
event.preventDefault();
var item;
if ((item= $(this).attr( 'href' ))=="saved") return false;
$(this).html("<div style='line-height:4em '>Saved</div>");
$(this).attr("href","saved");
var action ="add";
jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
var result=data.result;
if (result=="saved") {
self.html("<div>Saved</div>");
self.attr("href","saved");
}
}, "json")
.error(function() {
alert("error: unable to contact web service");
});
});
});
The returned JSON string from this request is { result: saved }. So as you can see you access the associated array as part of the data object. In my case data.result provided me with the value of result from the json string.
Note my example is for using an anchor tag to pass a value to send in the webservice call. In your case you will need to use a form.
If you're using jeoquery then just look at the html source of UI sample. It's showing the same autocomplete box that you might be trying to implement no custom code to write to parse returned JSON. Below code should work for you:
<input class="input-large" id="city" type="text"/>
$("#city").jeoCityAutoComplete();

Get custom JQGrid JSON data in gridComplete method

Here is a typical JQGrid JSON response:
{
"page":1,
"records":537,
"rows":[..],
"rowCount":10,
"total":54
}
Along with this, I want to send additional custom data. For example, I'd like to send the database time of the last search so that I can lazy-reload my grid whenever changes have occurred since then. Here is how I would like to send that data:
{
//Custom name-value pairs:
"nameValues":{"lastSearchTime":"2011/09/01:14:14:56"},
//Normal JSON data:
"page":1,
"records":537,
"rows":[..],
"rowCount":10,
"total":54
}
The problem is that JQGrid swallows up the JSON response rather than forwarding it to the gridComplete method. In other words, params is undefined in the following function:
function myGridComplete (params){
//params is undefined!
var JSONResponse = ?;//I need your help here!!!
globalGridVariables.lastSearchTime = JSONResponse.nameValues.lastSearchTime;
//Rest of grid complete method
..
}
Please let me know if there is a way to get access to the JSON response object in the gridComplete method, or if there is another supported way to add custom data to a JSON response.
Thanks much!
Note: I don't want to send this as a hidden column, because that would be inefficient.
You can use loadComplete instead of gridComplete. The loadComplete event has one parameter (for example data) which represent the full data from the server response inclusive all of your extensions.
Alternative you can rename the nameValues to userdata and use $('#list').jqGrid('getGridParam', 'userData') to get the value. See here for more information.
Moreover you can consider to use more HTTP caching (see here and here) for the aims which you described in your question.
You can use beforeProcessing that has the deserialized response and gets active before gridComplete and loadComplete.
For example:
beforeProcessing: function (data, status, xhr) {
myArray = data.rows;
}
And just to make it more clearer from the documentation:
Below is the execution order of the events when a ajax request is made
beforeRequest
loadBeforeSend
serializeGridData
loadError
beforeProcessing
gridComplete
loadComplete