Problems displaying .json values - javascript

I'm having trouble displaying two values on the screen( high-top and category):
This is my code:
$.getJSON('data.json', function(obj){
$.each(obj["best-seller"], function(key, value){
console.log(value.title);    
console.log(value.price); 
console.log(value.higth-top); 
console.log(value.category); 
$("#produto").append(" <b>"
+value.title+"<br/>"
+value.price+"<br/>",
+value.category+ "<br/>",
+value.higth-top+ "<br/>",
"</b>"
);
});
});
Note: Category is shown perfectly on the console, but in html it is returned NaN
And the higth-top is returned NaN in the console and also in the Html
Other values are normally displayed
I search the data in a .json, like this:
{
"best-sellers": [
{
"title": "Chuteira Nike HyperVenomX Proximo II Society",
"price": 499.9,
"installments": {
"number": 10,
"value": 49.9
},
"high-top": true,
"category": "society",
"image": "aaaa.jpg"
}
]
}

Just remove the commas inside the append.
Right now you've separated the variables by commas, giving append multiple arguments, and the plus signs acts as coercion to numbers instead of string concatenation, giving you NaN instead of the expected string
$("#produto").append(" <b>" + value.title +
"<br/>" + value.price +
"<br/>" + value.category +
"<br/>" + value['higth-top'] +
"<br/></b>"
);
Also note that hyphens aren't valid in dot-nation, as they also mean "subtract", you'd have to use bracket notation for the property higth-top

You cannot concatenate a string with commas so you have to remove them, moreover hyphens are not allowed in dot-notation
value.higth-top
here javascript understands "subtract top to value.high"
Write it as follows
$("#produto").append(" <b>" + value.title +
"<br/>" + value.price +
"<br/>" + value.category +
"<br/>" + value['high-top'] +
"<br/></b>"
);

Related

Comparison of two String is not working in script

Actually in my function I have to compare two strings, the one string I fetch through the db and compare to the null string but it's not working..
Here is my Code:
order.items.forEach(function(entry) {
result += '<tr>'
+ '<td>'+'<font size=2>'+ a++ + '</font>'+ '</td>'
+ '<td>' +'<font size=2>'+ entry.title + '</font>'+ '</td>'
+ '<td>' +'<font size=2>'+ entry.quantity + '</font>'+'</td>'
if(entry.personalization == 'null') //here is the problem
+ '<td>' +'<font size=2>'+ 'No Personalization' + '</font>'+'</td>'
else
+ '<td>' +'<font size=2>'+ entry.personalization + '</font>'+'</td>'
+ '</tr>';
})
result +='</table>';
$('.modal-body').html(result);
Use console.log(entry.personalization) to check value.
Dhara's answer should work...
I also use it for null check.
(!entry.personalization)
or try
(entry.personalization != "")
To check empty or null string in jquery:
if (!entry.personalization) {
// is empty
}
As mentioned in your question, if one string i fetched by you and the other string is "null", It is a clear question of string comparison and not checking null...
Javascript has localeCompare() method to compare strings..
You should use
entry.personalization.localeCompare("null");
or its inverse
var n = "null";
n.localeCompare(entry.personalization);
this function returns boolean.
You don't need to wrap null around ''.
Simply use :-
if(entry.personalization == null)

Reference object in an array in an object javascript

I hope that title makes sense... I'm very new to doing anything with Javascript, and I've been searching for a while now.
I'm using Node-RED to receive an HTTP POST containing JSON. I have the following data being posted in msg.req.body, and want to pull out objects inside of targets:
{
"policy_url": "https://alerts.newrelic.com/accounts/xxxxx/policies/7477",
"condition_id": 429539,
"condition_name": "Error rate",
"account_id": 773524,
"event_type": "INCIDENT",
"runbook_url": null,
"severity": "CRITICAL",
"incident_id": 50,
"version": "1.0",
"account_name": "Inc",
"timestamp": 1436451988232,
"details": "Error rate > 5% for at least 3 minutes",
"incident_acknowledge_url": "https://alerts.newrelic.com/accounts/xxxxxx/incidents/50/acknowledge",
"owner": "Jared Seaton",
"policy_name": "Default Policy",
"incident_url": "https://alerts.newrelic.com/accounts/xxxxxx/incidents/50",
"current_state": "acknowledged",
"targets": [{
"id": "6002060",
"name": "PHP Application",
"link": "https://rpm.newrelic.com/accounts/xxxxxx/applications/6002060?tw[start]=1436450194&tw[end]=1436451994",
"labels": {
},
"product": "APM",
"type": "Application"
}]
}
I want to format a string to send via TCP to insert an event into our event management system. So I tried the following:
msg.payload = msg.req.body.targets[0] + "|" + msg.req.body.severity + "|" + msg.req.body.current_state + "|" + msg.req.body.details + "|" + msg.req.body.condition_name + "\n\n";
return(msg);
This results in a message of:
[object Object]|CRITICAL|acknowledged|Error rate > 5% for at least 3 minutes|Error rate
I've tried a few different things, but I either get a null return, or the [object Object]. It feels like I'm close...
Can anyone assist?
Thanks in advance.
target[0] is an object and that is why you see [object Object].
You should instead do msg.req.body.targets[0].name to access the property of that object.
The result message would look something like this
PHP Application|CRITICAL|acknowledged|Error rate > 5% for at least 3 minutes|Error rate
You want JSON.stringify()
msg.payload = JSON.stringify(msg.req.body.targets[0]) + "|" + msg.req.body.severity + "|" + msg.req.body.current_state + "|" + msg.req.body.details + "|" + msg.req.body.condition_name + "\n\n";
return(msg);
This will turn the object that is stored in the first slot in the target array into it's string representation.

Insert JavaScript variable into JSON

I want to insert a js variable into json (to show a message on slack).
I have tested this :
"fields":[
{
"title": "Reported by:",
"value": "'+ user + '",
"short": "false"
},
but it doesn't work and show me this :
Reported by:
'+ user +'
Thanks you !
It looks to me like you should be doing something like:
"value": "'" + user + "'",
Before user was still part of the string expression.
This is called string concatenation:
{
"title": "Reported by:",
"value": "'" + user + "'",
"short": "false"
}
The value will produce a string with the combined values, such as if user were a string value of "Jamen", the concatenated value of value would be "'Jamen'"

Formatting bible verse reference with regex in javascript

I'm trying to monospace bibleverse references so that single digit chapters or verses have a leading space.
So "4:5" becomes " 4: 5" and "3:21" becomes " 3:21".
I'm really having problems writing the regex, please help.
I've tried many variations but they essentially boil down to (^\d|\d$), (^\d{1}|\d{1}$) and (^[^0-9]\d|[^0-9]\d$) and many combinations between them
inRef = inChapter + ':' + inVerse;
var inReg = /(^[0-9]{1}|[^0-9][0-9]{1}$)/g;
inRef = inRef.replace(inReg," $1");
console.log(inRef);
Alot of the results I'm getting from my efforts turn references like "6:15" into " 6: 1 5" or " 6:1 5"
Thank you in advance.
Why a regex at all? You've already got the chapter/verse as separate data BEFORE you combined them into the x:y format, so do the formatting there while they're still seperate strings:
if (inChapter.length == 1) { inChapter = ' ' + inChapter }
inRef = inChapter + ':' + inVerse;
Using a regex for this uber-simplistic transformation is akin to nuking a city to get some dust off a shelf instead of using a feather duster.
Given the strings inChapter and inVerse, you could do something like this:
inRef = (" " + inChapter).slice(-2) + ":" + (" " + inVerse).slice(-2)
Note there are two spaces there " " and I'm assuming inChapter and inVerse are only ever 1 or 2 digits.
Edit: Since you need three digits and I assume you still want these to line up, you could do this:
var pad = " "; // this is now THREE spaces!
inRef = (pad + inChapter).slice(-pad.length) + ":" + (pad + inVerse).slice(-pad.length)
So now if you run all your inChapter and inVerse pairs through this, you should get strings that line up like this:
100:100
20:100
2:100
100: 10
100: 1
10: 10
10: 1
1: 1

Parsing Complex JSON Javascript

I am able to parse JSON that returns simple data, with JSON.parse but I am having trouble with data that returns objects, dates, strings, etc..
var theData=JSON.parse(theData);
Something like this JSON.parse returns [Object] object back with no data at all (I can see the data is being successfully returned because it returns all the data as a string if I have JSON.parse turned off).
{
"AppName": "TheName",
"AppUrl": "https:\/\/app\/icons\/unknown.png",
"aGUID": "45c055d2-2edc-d4444"."DateCreated": "8\/23\/2012 11:04AM", {
"ID": "yser123",
Name ":" User "}
}
What is the best way to go about parsing this data in javascript(I am not able to use jquery)?
Note: I had wrote the JSON assume its valid
Here is the code I am using to retreive the data..
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "ClientService.svc/REST/GetDetail", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
return serverResponse;
First and foremost, don't use synchronous XHR. Rewrite your JavaScript to be asynchronous.
function getDetail(cb) {
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "ClientService.svc/REST/GetDetail", true);
xhReq.onreadystatechange = function() {
if (xhReq.readyState == 4) cb(xhReq.responseText);
}
xhReq.send(null);
}
// to call:
getDetail(function(data) {
JSON.parse(data);
}
Second, your problem is not that JSON is being parsed incorrectly. It's your debugging call to alert. When you pass the serverResponse object, alert coerces the object into a string by calling the object's toString method, which simply returns '[object Object]'.
Try console.log. Objects can be inspected in the console.
It actually sounds like this is working. If you call some thing like this:
alert(JSON.parse(serverResponse))
It will display [object Object] which is correct. If you call
alert(JSON.parse(serverResponse).appName)
You should see the appName. If you are not seeing "SyntaxError"s being thrown, JSON.parse() is working
Your JSON format is wrong and the data needs to be a string.
So, this will work (I broke the lines to improve readability):
var data = "{" +
" \"AppName\": \"TheName\", " +
" \"AppUrl\": \"https:\/\/app\/icons\/unknown.png\", " +
" \"aGUID\": \"45c055d2-2edc-d4444\", " +
" \"DateCreated\": \"8\/23\/2012 11:04AM\", " +
" \"foo\": { " +
" \"ID\": \"yser123\", " +
" \"Name\":\"User\"" +
" }" +
"}";
var obj = JSON.parse(data);
alert( obj.AppName );
Of course, if you use simple quotes as string delimiter, the code would be:
var data = '{' +
' "AppName": "TheName", ' +
' "AppUrl": "https:\/\/app\/icons\/unknown.png", ' +
' "aGUID": "45c055d2-2edc-d4444", ' +
' "DateCreated": "8\/23\/2012 11:04AM", ' +
' "foo": { ' +
' "ID": "yser123", ' +
' "Name":"User"' +
' }' +
'}';
This not works:
var data = "{" +
" 'AppName': 'TheName', " +
" 'AppUrl': 'https:\/\/app\/icons\/unknown.png', " +
" 'aGUID': '45c055d2-2edc-d4444', " +
" 'DateCreated': '8\/23\/2012 11:04AM', " +
" 'foo': { " +
" 'ID': 'yser123', " +
" 'Name': 'User'" +
" }" +
"}";
jsFiddle: http://jsfiddle.net/9pmdm/1/

Categories