Getting information from array of array - json

I've tried getting information with JSON only with one function, and it works fine. When it becomes two or more though it was pointed out that an array of array should be used.
How can you decode this information?
get.php
$response = array("home"=>$home, "topr"=>$top);
echo json_encode($response);
test.js
$(document).ready(function() {
$.get("php/get_ratings.php")
.done(function(data) {
var results = jQuery.parseJSON(data); // Should I change this?
$.each(results, function(i, value) { // Or this?
})
});
});

What PHP calls "arrays" are not what most languages call "arrays," including both JSON and JavaScript. Your response will be in this form:
{"home": something, "topr": something}
In your code:
No, you don't need to parse it, jQuery will do that for you if it's being sent correctly (e.g., with Content-Type: application/json).
You can access .homeand .topr properties on the object you receive.
E.g.:
$( document ).ready(function() {
$.get( "php/get_ratings.php")
.done(function(data) {
// use data.home and data.topr here
});
});
What you do with them depends on what they are, which you haven't shown. If they're numerically-index arrays (what most languages call arrays), your response will look like this:
{"home":["stuff","here"], "topr": ["stuff","here"]}
...and .home and .topr will be JavaScript arrays.
If they're PHP associative arrays like your top level thing, then they'll come through as objects, with properties named after the keys of the associative array.

Related

Collecting a value from JSON file with ember.js

I am trying to pass a simple variable value into an HTML file using ember.js. My value is contained within a json file called value.json.
My HTML code is as follows:
<h1>I won {{App.moneyvalue}} today!</h1>
However when I pass the json call via ember, it think that the entire call is a variable:
App = Ember.Application.create({
moneyvalue: function () {
return $.getJSON( "js/value.json", function( data ) {
return data.tot;
});
}
}
And returns the following:
I won function () { return $.getJSON( "js/donors.json", function( data ) { return data.tot; }); } today!
As it seems to think that moneyvalue is a string variable as opposed to a value?
The jSON file is superbasic
{
"tot": 100
}
Where is this going wrong?
you're supplying Handlebars with a function, generally you would use a computed or normal property on the object. In this case you really just shouldn't define it in the application scope either, I'd recommend using an application route (it's the root route of your app).
App.ApplicationRoute = Ember.Route.extend({
model: function(){
return $.getJSON( "js/value.json");
}
});
Then in your handlebars just use
<h1>I won {{tot}} today!</h1>
Here's an example: http://emberjs.jsbin.com/OxIDiVU/576/edit

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.

JSON to usable array javascript

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".

jQuery.getJSON and jQuery.parseJSON return [object Object]?

EDIT: I've gotten the "famous question" badge with this question, so I figured I'd come back to it and stick what happened to me right at the very tippy top for people searching it to get an answer right away.
Basically, I was new to JSON. JSON is an object (obviously), as it contains all kinds of stuff! So I was like "Hey, javascript, just pop up an alert with all of this JSON data", expecting it to give me the JSON data as a string. But javascript doesn't do that (which is good!), so it was like "Hey, this is how we display objects, [object Object]".
What I could've done is something like alert(obj.DATA[0][1]) and it would've shown me that bit of the object.
What I really wanted was to verify that I was making good JSON data, which I could've checked with JSON.stringify.
Anyway, back to our regularly scheduled questions!
I'm trying to get some JSON data with an ajax call, but jQuery doesn't seem to like my JSON.
if I do something like:
function init2() {
alert("inside init2");
jQuery.ajax({
url: "/Mobile_ReportingChain.cfm",
type: "POST",
async: false,
success: function (data) {
alert(data);
var obj = jQuery.parseJSON(data);
alert(obj);
}
});
}
I get this as from alert(data):
{"COLUMNS":["MFIRST_NAME","MLAST_NAME","MMDDL_NAME","MEMPLY_ID","MAIM_NBR","EMPLY_ID"],
"DATA":[
["FNAME1 ","LNAME1 ","MI1 ","000-14-7189","026-0010","000-62-7276"]
,["FNAME2 ","LNAME2 ","MI2 ","000-01-2302","101-1850","000-14-7189"]
,["FNAME3 ","LNAME3 ","MI3 ","000-91-3619","102-1000","000-01-2302"]
,["FNAME4 ","LNAME4 ","MI4 ","000-25-9687","102-1000","000-91-3619"]
]}
which JSONLint says is valid json. alert(obj) gives me this, however:
[object Object]
adding dataType: "json" or "text json" just makes it report [object Object] at alert(data).
I'd really like to get this figured out, does anyone know why it's doing this? I'm pretty new at jQuery, my goal is to get an array for each of the columns. The same code I'm using has worked on a different page it looks like, which is what's bothering me the most.
The alert() function can only display a string of text. As its only parameter it takes a string or an object. The object will however be converted into a string that can be displayed.
When fetching JSON through jQuery, the $.ajax() method will automatically parse the JSON and turn it into a JavaScript object for you. Your data variable is therefor a JavaScript object, and not a JSON string as one might expect.
Since alert() only can display strings, when trying to alert your data object, your object will be turned into its string representation. The string representation of a JavaScript object is [object Object].
For debug-purposes you can use console.log(data) instead. You can then inspect the object and its content through the console in your browsers developer tools.
function init2() {
jQuery.ajax({
url: "/Mobile_ReportingChain.cfm",
type: "POST",
dataType: "json",
async: false,
success: function (data) {
console.log(data);
}
});
}
If you for some reason still want to alert the JSON-data, then you would have to turn your data object back into a JSON-string. To do that you can make use of JSON.stringify:
alert(JSON.stringify(data));
it wants a string
var obj = $.parseJSON(JSON.stringify(data));
try sending that object to console.log. You'll get a clearer picture what does it contain.
Also, put dataType: 'json' and remove parseJSON because it's all the same.
This is how it's supposed to work. Your JSON becomes a javascript object. You can then manipulate that object as a regular javascript object.
data.COLUMNS for instance should return an array.
[object Object] is the string representation of a javascript object.
Try accessing properties of the object.
alert(data.COLUMNS[0]);
jQuery.parseJSON will convert the json string into json object so alert(obj) will show you [object Object] since it is an object.
If you want to see what obj contains then use console.log(obj) and then check console log message.
$.getJSON( "UI/entidades.json.php", function(data){
result = JSON.stringify(data);
alert(result)
console.log(result)
})
(I knows this is an jquery problem; but just bear with me for a min. so that i can explain why this problem occurred to me in the first place).
I wanted to fill in the gaps made my deletion of records in my MySQL table ( primary key that was auto increment. So when records where deleted in between my id had missing keys. I though some mechanism to show those missing keys. So i created the code that created an array through a loop then deleted those keys that were present and echo backed that array (of course json_encode that array).
But to my amazement what ever I did it always end up giving me [object Object].
It baffled me a lot that were was the problem.
Solution: Just realigning the array and all my problem gone.
Below I would give an simplified example.
<!DOCTYPE html>
<html>
<head>
<script src="../js/jquery/jquery3.x/jquery-3.3.1.min.js"></script>
<title></title>
<script type="text/javascript">
$(function () {
$('#generate').click(function () {
$.get('tmp2.php?tab=1', function (data) {
var retStr = '<table>';
var par = $.parseJSON(data);
$(par).each(function () {
retStr += '<tr><td>' + this + '</td></tr>';
});
retStr += '</table>';
$('#res').html(retStr);
});
});
});
</script>
</head>
<body>
<input type="button" value="generate" id="generate" />
<div id="res"></div>
</body>
</html>
And the controller
<?php
if (!empty($_GET['tab'])) {
$ids = array();
for ($i = 0; $i < 50; $i++)
$ids[] = $i;
for ($i = 0; $i < 50; $i = $i + 2)
unset($ids[$i]);
// echo json_encode($ids); // this will generate [object Object]
$res = array();
foreach ($ids as $key => $value) {
$res[] = $value;
}
echo json_encode($res);
exit();
}
?>