2

Im using an ajax json response to build some html to place in a webpage. Occasionally I'll come across an empty value in my json. This results in an empty object being placed into the html.

I would prefer not to check that each value is not an object, as that doesn't seem efficient. Is there a better way? my code works like this

var firstVar=jsonObj.fristVar;
var secVar=jsonObj.secVar;
var thirdVar=jsonObj.thirdVar;
var fourthVar=jsonObj.fourthVar;
...
var htmlResponse='<div class="'+firstVar+'">'+secVar+'<span class="'+thirdVar+'">'+fourthVar+'</span>...';
jQuery("body").html(htmlResponse);

2 Answers 2

2

If you want to specify default values when they are null, you can just do this:

var firstVar = jsonObj.firstVar || '';
var secVar = jsonObj.secVar || 'No Value';
...

Unrelated to your question, have you looked at an implementation of jQuery templating?

Sign up to request clarification or add additional context in comments.

3 Comments

That will set the default value not only when the members are null, also when they are 0, false, undefined, empty string and NaN.
The code you've written above makes sense, and it should work, but I'm still getting the response of "[object object]" when using var firstVar=jsonObj.firstVar || ''; - When I alert(firstVar.toSource), I get ({}). Any idea why I'm still getting this?
also, I wasn't familiar with jQuery templating before, and I'm not really sure why it is beneficial, but I'll dig into it deeper. Thanks for expanding my knowledge.
1

You could use a tertiary operator:

var firstVar = (jsonObj.fristVar != null) ? jsonObj.fristVar : "some default value";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.