对int转换感到困惑

Confused on int conversion

我正在编写一个执行以下操作的节点 js 程序。

  1. 获得 json.
  2. 解析它。
  3. 打印到控制台。

目前我能很顺利的完成以上三件事。但是我的问题出现在这里。我正在尝试将值从 json 转换为 int。下面是我的示例数据。

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

从上面的 json 我需要 int 格式的 dueAmount 所以我尝试了下面的代码。

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));

当我 运行 这个程序时,我得到的输出是

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

我需要在哪里打印 4000 而不是 NaN

此外,令我感到困惑的是,type 显示为 number,但给出的值是 NaN

请告诉我哪里出错了,我该如何解决。

谢谢

试试下面的代码(不需要使用JSON.stringify)

    var userDueDate =res.Items[0].dueDate;
    var userDueAmount = res.Items[0].dueAmount;
    var userTotalBalance = res.Items[0].totalBalance;
    var intUsingParseInt = parseInt(userDueAmount);

    console.log('by using Parse : ' + intUsingParseInt + ' and the type is :' + (typeof intUsingParseInt));

假设 res 是一个 JSON 对象。您可以简单地使用 parseInt 函数来获取数字格式。

var am = parseInt(res.Items[0].dueAmount)

你不应该在这里使用 JSON.stringify。因为它将 JSON 对象转换为字符串。

JSON是一个被包裹成字符串的JS对象:

let json = "{"dueAmount":"4000"}" - 是一个 JSON 对象,
let jsObj = {"dueAmount":"4000"} 不是。

如果收到JSON对象,需要通过

转为JS对象
let result = JSON.parse(json)

然后是

parseInt(result.dueAmount)