Search code examples
jsonnode.jsparseint

Confused on int conversion


I'm writing a node js program that does the below.

  1. get the json.
  2. parse it.
  3. print to console.

Currently I'm able to do the above three things very smoothly. But my problem comes up here. I'm trying to convert a value from json to int. and below is my sample data.

{
    "Items": [
        {
            "accountId": "12345",
            "pin": "1234",
            "userId": "user1",
            "dueDate": "5/20/2017",
            "_id": "2",
            "dueAmount": "4000",
            "totalBalance": "10000"
        }
    ],
    "Count": 1,
    "ScannedCount": 4
}

and from the above json I'll need the dueAmount in int format so I tried the below code.

var userDueDate = JSON.stringify(res.Items[0].dueDate);
var userDueAmount = JSON.stringify(res.Items[0].dueAmount);
var userTotalBalance = JSON.stringify(res.Items[0].totalBalance);
var intUsingNumber = Number(userDueAmount);
var intUsingParseInt = parseInt(userDueAmount);
console.log('by using Number : ' + intUsingNumber + ' and the type is :' + (typeof intUsingNumber));
console.log('by using Parse : ' + intUsingParseInt + ' and the type is :' + (typeof intUsingParseInt));

and when I run this program I get the output as

by using Number : NaN and the type is :number
by using Parse : NaN and the type is :number

Where in I need to print 4000 instead of NaN.

Also, what I'm confused is, the type is showing it as a number, but the value is given as NaN.

Please let me know where am I going wrong and how can I fix it.

Thanks


Solution

  • JSON is a JS object wrapped as a string:

    let json = "{"dueAmount":"4000"}" - is a JSON object,
    let jsObj = {"dueAmount":"4000"} is not.

    If you receive a JSON object, you need to convert it to JS object by

    let result = JSON.parse(json)
    

    and then

    parseInt(result.dueAmount)