Interesting Features about JSON.stringify

If you’ve been working with JavaScript in the past, you probably used this cool JSON.stringify method to convert some type of JavaScript value into its JSON string representation. Such method can be used with simple data types like strings and numbers. We probably have used this daily, but unaware of the extra feature available to use in JSON.stringify method. Therefore, in this post we’re going to explore some basic features we can use instantly in our next JavaScript code. To follow along, check out this demo link.

The basic

var cities= ['Miami', 'Orlando', 'Los Angeles', 'New York', 'Chicago'];
var json = JSON.stringify(cities); 

console.log(json);
//["Miami","Orlando","Los Angeles","New York","Chicago"]

If you look closely to the comment in the code snippet above, the array is printed out with no spaces and the single quotes are updated to double quotes.

JavaScript Object Conversion

In some cases you might be working with a JavaScript Object and want to convert it into JSON.

const person = {
  firstName: 'Paul',
  lastName: 'Johnson',
  age: 50,
  jobTitle: 'Manager'
}
var json = JSON.stringify(person);

console.log(json);
//{"firstName":"Paul","lastName":"Johnson","age":50,"jobTitle":"Manager"}

Again, as you can see the object is converted into a string and each property inside the object is shown as well as its value.

Working with Unsupported DataTypes

Not all data types supported by JavaScript can be converted in JSON. Types such as Strings, numbers, booleans, null, arrays, and objects are supported. However, date objects, regular expressions, undefined, and functions are not. How JSON.stringify deals with unsupported data types may differ if they are contained in an object or an array.
In case you have a complex object that can’t be serialized, it will be converted into an empty object or omitted. So beware of that when working with JSON.stringify. Here’s a quick snippet below showing a function and a complex credit object. Let’s see how that goes.

const book = {
  title: 'JSON Stringify Example',
  description: 'Providing great example on how to use JSON stringify',
  year: '2020',
  isOverdue: function() {
    // code here
  },
  credits: new Map([
    ['Jacque Roma'],
    ['Darline Raroule']
  ])
}
var json = JSON.stringify(book);

//{"title":"JSON Stringify Example","description":"Providing great example on how to use JSON stringify","year":"2020","credits":{}}

As you can see above in the output comment the credit object is indeed empty and isOverdue is removed.

Working with the replacer parameter in JSON.stringify

According to this Mozilla postthe replacer parameter can be either a function or an array. This function receives the actual key and value on which the JSON.stringify method is operating on. You are able to change the representation of the value with the function’s return value.
Let’s look at a quick example below on how to use the replacer as a function.

function replacer(key, value) {
  if (value < 1000) {
    return undefined;
  }
  return value;
}

var reviews = {
  books: 5000,
  cars: 3000,
  house: 999,
  boat: 2000
};
json = JSON.stringify(reviews, replacer);
console.log(json);
//{"books":5000,"cars":3000,"boat":2000}

After running the script above, because of the replacer function house is now printed out in the output. This is one way to remove unwanted values from the result.

However, when replacer is an array, the array's values will dictate what returned in the resulting JSON string. Here's a quick example below.

var reviews = {
  books: 5000,
  cars: 3000,
  house: 999,
  boat: 2000
};
json = JSON.stringify(reviews, ['books', 'house','boat'] );
console.log(json);
//{"books":5000,"house":999,"boat":2000}

Use of the space argument

JSON stringify has a third argument which you can use to control the spacing in the final string.

  • Use a number as the third argument ==> will cause each level in the stringification to be indented with this number of space characters up to 10.
    var reviews = {
      books: 5000,
      cars: 3000,
      house: 999,
      boat: 2000
    };
    json = JSON.stringify(reviews, ['books', 'house','boat'], 2);
    console.log(json);
    
    //example result below
    //{
    //  "books": 5000,
    //  "house": 999,
    //  "boat": 2000
    //}
    
  • Use a string as the third argument ==> will cause each level to be indented by this string (or the first ten characters of it). We'll use the same example above.
    var reviews = {
      books: 5000,
      cars: 3000,
      house: 999,
      boat: 2000
    };
    json = JSON.stringify(reviews, ['books', 'house','boat'], 'xx');
    console.log(json);
    
    //example result below
    //{
    //xx"books": 5000,
    //xx"house": 999,
    //xx"boat": 2000
    //}
    

To conclude, I would advise that you try it out for yourself and if this new to look more into the documentation.

How to create a simple Todo list Using Jquery

Yes, you heard it, a simple doto list using Jquery. We all know the famous hello world applications when we’re first learning a language. Now, it’s the todo app. In this post I am going to create a simple web todo application using HTML5, CSS3 and Javascript(jQuery).
You can develop this todo application in any text editor and debug in any browser. I’m using Plunker to code this due to its simplicity. You can follow along with using this Plunker demo link

Todo list Using Jquery – Project Setup

First things first, we need to set up our project. Let’s add a new index.html file to our plunker project as shown below.

  
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <link data-require="bootstrap@3.3.6" data-semver="4.1.3" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />
    <script data-require="bootstrap@3.3.6" data-semver="4.1.3" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="jquery" data-semver="3.2.1" src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div class="col-md-12">
      <h1>Simple Todo Demo!</h1>
      <p>Click on row to delete newly added entry.</p>
      <div data-role="content">
        <ul class="list-group" id="taskListSection">
          <li class="list-group-item active">Todos</li>
          <li class="list-group-item ">1. Example of Existing task</li>
          <li class="list-group-item ">2. Example of Existing task</li>
        </ul>
        <br />
        <fieldset class="ui-grid-a">
          <div class="ui-block-a">
            <textarea placeholder="Enter task" id="taskInputText" cols="50" maxlength="128"></textarea>
          </div>
          <div class="ui-block-b">
            <input type="button" class="btn btn-success" value="Submit" id="taskBtn" />
          </div>
        </fieldset>
      </div>
    </div>
  </body>

</html>
  

Nothing too fancy in that html code. We have a heading and paragraph to let user know to click newly created task. Next is an unordered list group from bootstrap 4 showing 2 items to start with. Think of those two items as existing data from a database. Next is a simple textarea to allow user to type new task entry to add to the list. Last, we have a button which will fire the add operation when user click on it.

Add script to handle add and delete tasks


// Add your javascript here
$(function(){
  $("h1").animate({
    "margin-left": "100px"
  }, "slow");
  

$('#taskBtn').click(function() {
  
    var newTask = $('#taskInputText').val();

    if(newTask !== '') {
      
        var count = $("#taskListSection").children().length;
        
        $('#taskListSection').append('<li class="list-group-item deletetask bg-success">' + count + '. '+ newTask + '</li>');
       
        $('#taskInputText').val('');
        
        deleteTasks();
        
        setTimeout(function(){
          $('#taskListSection li.bg-success').removeClass('bg-success');
        },1000); 
      
    } else {
        alert('Come on, you\'re better than that');   
    }
});  
});

function deleteTasks(){
 $('.deletetask').click(function(){
    $(this).remove();
}); 

}

Again, a simple javascript file containing animation for the heading of the page upon loading. Then, I have a click event listener for when user wants to add a new task to the list. A one second delay is added after the new entry is added to the list and row is highlighted. Then, it is unhighlited after the one second is expired.
A delete function is in there as well to remove the item from the list. Very basic.