javascript check if JSON key exists and display the value - javascript

I've been tinkering with Z-Wave lately and I'm trying to make a page to include/exclude their products. But it's not going too well. I'm trying to check if a JSON key exists then display it on the page. I get
TypeError: data.controller is undefined
Here is the code:
window.setInterval(function(){
getData();
}, 2000);
function getData()
{
var milliseconds = (new Date).getTime();
var time = milliseconds.toString().substr(0, milliseconds.toString().length - 3) ;
$.postJSON( "http://192.168.1.102:8083/ZWaveAPI/Data/" + time, function( data ) {
if(data.controller.lastExcludedDevice.value) alert("EXCLUDED SOMETHING");
if(data.controller.lastIncludedDevice.value) alert("INCLUDED SOMETHING");
});
}
$.postJSON = function(url, data, callback, sync) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
sync = sync || callback;
callback = data;
data = {};
};
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: callback,
error: callback,
async: (sync!=true)
});
};
Json:
{
"controller.data.controllerState": {
"value": 0,
"type": "int",
"invalidateTime": 1424781697,
"updateTime": 1425338938
},
"controller.data.lastIncludedDevice": {
"value": 42,
"type": "int",
"invalidateTime": 1424781697,
"updateTime": 1425338938
},
......
Any help is greatly appreciated.

if the dots are part of the key you need to use the [] notation.
for example
if (data['controller.data.controllerState'].value) ...
or
if (data['controller.data.lastIncludedDevice'].value) ...

Try this:
if(data.controller &&
data.controller.lastExcludedDevice.value)
alert("EXCLUDED SOMETHING");
Think of it this way: console.log({}.x) prints "undefined." console.log({}.x.y) throws an error. You're allowed to work with undefined but it throws an error if you try to access properties of it.
Use the short-circuiting property of && to expedite this check:
if(a && a.b && a.b.c && a.b.c.d) {
console.log("Not an error to print", a.b.c.d);
}{

Related

what's the correct way of pulling from a JSON file with jQuery/plain JS?

Solved
Turns out I messed up my JSON while trying to fix it. Thanks for helping. Showed me some new methods to use json :)
I searched through a lot of other questions, tried the responses, some did something others just threw an error. If it worked, it logged this whole list of metadata (including the json data I want) to the console:
{…}
​
abort: function abort(e)​
always: function always()​
catch: function catch(e)​
done: function add()​
fail: function add()​
getAllResponseHeaders: function getAllResponseHeaders()​
getResponseHeader: function getResponseHeader(e)​
overrideMimeType: function overrideMimeType(e)​
pipe: function pipe()​
progress: function add()​
promise: function promise(e)
​
readyState: 4
​
responseText: "<JSON content>"
​
setRequestHeader: function setRequestHeader(e, t)​
state: function state()
​
status: 200
​
statusCode: function statusCode(e)
​
statusText: "OK"
​
then: function then(t, n, r)​
<prototype>: Object { … }
So, my question is: how do I get the json contents from this?
Code used:
function start() {
var j = $.ajax({
url: 'users.json',
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
}
});
}
Json:
"UsersByID":[ {
"id": 1
"Name": ["K", "L", "Smiths"],
"Birthday": ["03", "10", "1987"],
"Username": "user1",
"Password": "verysafepassword",
"Hollidays": [{
"HollidayId": 1
"HollidayType": 2,
"AmountOfPeople": 5,
"Date": ["18", "08", "2020"]
}{
"HollidayId": 2
"HollidayType": 3,
"AmountOfPeople": 2,
"Date": ["24", "10", "2020"]
}
}]
}]
}
}
What you normally do (in plain javascript) is to filter throughthe delivered JSON. Since I do not know what you want to filter, some pseudo code how it works:
function start() {
var j = $.ajax({
url: 'users.json',
type: "GET",
dataType: "json",
success: function (response) { //data is a keyword so better use response
console.log(response);
response.data.forEach(function(field) { // we iterate through each field in the JSON
if (field.typeField == "UsersByID") { // Given the JSON part looks like {"UsersByID":{"myBigData": "secrets","yourBigData": "noSecrets"}}
console.info("My content found");
// Do whatever you have to do with the content
}
}); // for each END
}
});
}
EDITT To process the JSON there are different posibilities If you know what is comming you filter like I have done above and then do something with the result.
Another way if you don't have to extract, but the whole response is the needed JSON you do as follows (and of course you can combine)
function start() {
var j = $.ajax({
url: 'users.json',
type: "GET",
dataType: "json",
success: function (response) { //data is a keyword so better use response
console.log(response);
var myObj = JSON.parse(response);
// Do whatever you have to do with myObj e.g.
var u_username = myObj.Username; // you retrieve from the object with the field names
// when nested you get a new object and then you retrieve
var objHollidays = myObj.Hollidays;
var u_HollidayId = objHollidays.HollidayId;
// OR you iterate over all objHollidays
objHollidays.HollidayId.forEach(function(field) { // we iterate through each
//Do whatever you need
});
}
});
}
Parsing Dates
Date objects are not allowed in JSON.
If you need to include a date, write it as a string.
You can convert it back into a date object later:
var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

Use form naming to reach json data in Javascript/jQuery?

I have the following input name: dynamic[elements][1][slider][image1]
When performing an ajax call, a json response with settings and its value is returned.
$.ajax({
url: '/get/settings',
type: 'POST',
data: formData,
async: false,
success: function (data) {
});
How can i get the value of dynamic[elements][1][slider][image1] the easiest way? It works to get the value like this:
data.dynamic.elements[1].slider.image1
So:
$.ajax({
url: '/get/settings',
type: 'POST',
data: formData,
async: false,
success: function (data) {
console.log(data.dynamic.elements[1].slider.image1);
});
But isn't their any better way of getting the value? The only identifier I have to get the value, is the name of the input field which is dynamic[elements][1][slider][image1]. So i would need to extract this string and put it together as data.dynamic.elements[1].slider.image1 to then make it a dynamic variable somehow (to finally get the value)?
Example ajax response:
{
"success": 1,
"dynamic": {
"elements": [
{
"title": {
"title": "Our beautiful topic"
}
},
{
"slider": {
"image1": "5zw3ucypzp3qham.png",
"image1_link": "hellor"
}
}
]
}
}
You may choose to write a generic function for the purpose of retrieving data from object. The function should look something like below. Though the function may not be foolproof but should be enough for proof-of-concept.
function getObjectData(target, path) {
// if the path is not in dot notation first convert
if (path.indexOf(".") == -1)
path = path.replace(/\[/g, ".").replace(/\]/g, "");
var parts = path.split(".");
return parts.reduce(function (acc, currentVal) {
return acc ? (acc[currentVal] || undefined) : acc;
}, target);
}
//usage
getObjectData(data, "dynamic.elements.0.slider.image1"); //undefined
getObjectData(data, "dynamic.elements.1.slider.image1"); //5zw3ucypzp3qham.png
getObjectData(data, "dynamic[elements][1][slider][image1]"); //5zw3ucypzp3qham.png
Hope this helps.

Scraping JSON data from an AJAX request

I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];

Not able to access JSON data in ajax jquery

I have a Jquery AJAX POST method.Which call a web method of asp.net.
The ajax method get a json data.
The data format is :
[
{
"Title": "Test2",
"Name" : "AMIT",
"IsRoot": "True"
},
{
"Title": "Test3",
"Name" : "AMIT1",
"IsRoot": "False"
},
{
"Title": "Test4",
"Name" : "AMIT2",
"IsRoot": "True"
}
]
I validate the dataformat in "http://jsonlint.com/" site and it's telling that dataformat is correct.
I want to loop through the data and access each of the attribute.But I am not able to get that.
I try to find the total array length which should be 3.But it's giving me 9(means each attribute )
I try
alert(data.d.length); // giving 9 (should give 3)
var jsondata = data.d;
alert(jsondata[1].Title); //undefined (should give Test3)
alert(jsondata[2].Title); //undefined (should give Test4)
alert(jsondata[1].Name); //undreined (should give AMIT1)
var key, count = 0;
for (key in data.d) {
if (data.d.hasOwnProperty(key)) {
count++;
}
}
alert(count); // giving 9 (should give 3)
any help is highly accepted.
My ajax calling method is
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetRootData",
dataType: "json",
success: function (data, textStatus) {
var jsondata = data.d;
alert(jsondata[1].Title);
alert(jsondata[2].Title);
alert(jsondata[1].MimeType);
var key, count = 0;
for (key in data.d) {
if (data.d.hasOwnProperty(key)) {
count++;
}
}
alert(count);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
and don't know why debugger also not working.. :(
Thanks everyone.Finally I solved the problem.
the solution is
var jsonObject = eval(data.d);
Now it's returning all the data fine..
alert(jsonObject.length); //Now it's returning 2
alert(jsonObject[1].Title); // it's returning Test3 now.
Thanks..

accessing json data from jquery

I'm creating an ajax app using jQuery 1.4.2 and I've tried using using get(), post() and the ajax() method itself. My php service returns:
[{"k":"label0","v":0.5},{"k":"label1","v":99.43},{"k":"label2","v":2.46},{"k":"label3","v":46.29},{"status":"OK"}]
in my success callback I have tried accessing as json.status and json[0][0]
but it always returns "undefined". what am I doing wrong?
function getSysinfo(source) {
var json = null;
$.ajax({
url: source,
type: 'POST',
dataType: 'json',
success: function (data) {
json = eval("(" + data + ")");
$('#data').html(json.status);
alert(json[0][0]);
refreshChart(json);
},
error: function (request, status, error) {
alert("REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
return json;
}
I've been googling this for days. How the heck do I access the returned data? any help would be appreciated.
To access that status value you would need:
data[4].status
This is because it is an object stored in the the fifth element in an array, with status being a property on the object.
Your JSON-data looks like this:
[
{
"k": "label0",
"v": 0.5
},
{
"k": "label1",
"v": 99.43
},
{
"k": "label2",
"v": 2.46
},
{
"k": "label3",
"v": 46.29
},
{
"status": "OK"
}
]
You would have to read your status using
json[4].status
with the 4 as a magical number or length-1 - not desirable. I would consider modifying your servers response to something more useful like this:
{
"status": "OK",
"entries": [ ... ] // add your data here
}
In your success callback try:
var parsed = $.parseJSON(data);
$.each(parsed, function (i, jsondata) {
alert( jsondata.k );
alert( jsondata.v );
});
You don't need the eval("("+data+")");. jQuery is automatically parsing the JSON response for you because you specified dataType:'json'
From the jQuery docs for dataType:
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
no need to use eval any more use below code which can be more for json
$.getJSON(url+query,function(json){
$.each(json,function(i,value){
});
});
nategood already wrote that you don't need do do anything with data, it's already an object.
In this case it's an array, if you like to access the status, you need to retrieve it from the last item of the data-array(that's where you'll find it in this array):
data[data.length-1].status
But maybe you should think about another structure of your JSON, it doesn't look very comfortable.
Something like that:
{
"items":[
{"k":"label0","v":0.5},
{"k":"label1","v":99.43},
{"k":"label2","v":2.46},
{"k":"label3","v":46.29}
],
"status":"OK"
}
...should be easier to handle, because you can simply access data.status instead of first looking where you may find it inside the response(what may be error-prone ).
The data parameter is the decoded JSON as you can see in this example:
http://www.jsfiddle.net/rLprV/1/
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formData,
showLoader:true,
success: function (response) {
var parsed = JSON.parse(JSON.stringify(response));
$.each(parsed, function (key, val) {
alert( val.name );
});
},
error: function (err) {
alert("Please enter a valid id")
}
});

Categories