Getting wrong parsing with JSON.parse? [duplicate] - javascript

This question already has answers here:
What is JavaScript's highest integer value that a number can go to without losing precision?
(21 answers)
Closed 2 years ago.
I have used the following text as input to JSON.parse()
let inputTxt = `{"result":[{"aliasName":null,"name":"SRDD","sort":0,"id":319488404634063872,"parentId":319472086895578112,"level":2},{"aliasName":null,"name":"Noodles","sort":11,"id":350368638463726592,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Sushi","sort":21,"id":350368638463726593,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Drink","sort":31,"id":350368638463726594,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Set","sort":41,"id":350368739890458624,"parentId":350368638434366464,"level":2},{"aliasName":"默认","name":"默认","sort":1,"id":319472086895578112,"parentId":null,"level":1},{"aliasName":null,"name":"Tendongo","sort":0,"id":350368638434366464,"parentId":null,"level":1}],"code":0,"message":"success[OK]","messageUuid":"437fcce5209d4d17b558403d4a8b859c","apiMessage":null}`
console.log(JSON.parse(inputTxt))
Here you can see the id for the category is different in the output.

The issue is with a big number. When you parse JSON. It is trying to hold a large number.
Max value can be seen as :
Number.MAX_SAFE_INTEGER // (253 - 1) => 9007199254740991
More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
const str = "319488404634063872"
console.log(Number(str)) // 319488404634063900
// OR
const num = 319488404634063872
console.log(num) // 319488404634063900
You can use replace function as workaround, before parsing convert it to string.
let inputTxt = `{"result":[{"aliasName":null,"name":"SRDD","sort":0,"id":319488404634063872,"parentId":319472086895578112,"level":2},{"aliasName":null,"name":"Noodles","sort":11,"id":350368638463726592,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Sushi","sort":21,"id":350368638463726593,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Drink","sort":31,"id":350368638463726594,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Set","sort":41,"id":350368739890458624,"parentId":350368638434366464,"level":2},{"aliasName":"默认","name":"默认","sort":1,"id":319472086895578112,"parentId":null,"level":1},{"aliasName":null,"name":"Tendongo","sort":0,"id":350368638434366464,"parentId":null,"level":1}],"code":0,"message":"success[OK]","messageUuid":"437fcce5209d4d17b558403d4a8b859c","apiMessage":null}`;
const format = (json) => json.replace(/\"id\":(\d+)/g, `"id":"$1"`)
console.log(JSON.parse(format(inputTxt)))

Related

Javascript rounding this number down 9703248444284653 [duplicate]

This question already has answers here:
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 1 year ago.
I'm sure this has something to do with floating point math or something, but I need to out how to correctly interpret this number 9703248444284653. Javascript apparently doesn't like it
If I just do this.
var test = 9703248444284653
console.log(test)
The result is 9703248444284652, which is obviously not correct. Problem is that 9703248444284653 is an id that can't be changed. I have no idea what to do with this.
Your value is larger than Number.MAX_SAFE_INTEGER.
console.log(9703248444284653n > Number.MAX_SAFE_INTEGER);
You should treat your IDs as BigInt values. So you can should probably store the values as strings and then parse them as BigInt values if you need to perform any math on them.
const
bigIntNative = 9703248444284653n,
bigIntConstructed = BigInt('9703248444284653');
console.log(typeof bigIntNative === 'bigint' && bigIntNative === bigIntConstructed);
console.log(`${bigIntNative}`);

How do I convert my HEX string into a number? [duplicate]

This question already has answers here:
How to convert decimal to hexadecimal in JavaScript
(30 answers)
Closed 3 years ago.
I wish to convert the whiteHex variable to a decimal using the parseInt() function, and store it in a variable, whiteDecimal.
var whiteHex = 'ffffff';
var whiteDecimal = parseInt(whiteHex);
I am unsure if the above is correct or not. The reason being, that I then wish to subtract 1 from whiteDecimal and store it in a variable offWhiteDecimal. This is where I am getting stuck. How can I subtract one from the ffffff hex value? Am I missing something within the parseInt function?
You're looking for this:
var whiteDecimal = parseInt(whiteHex, 16)
console.log(whiteDecimal - 1);
ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Syntax

Strange maths while filtering array by elements in another array [duplicate]

This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 4 years ago.
I was trying to remove ids from a new request that have already been requested. In the code below I was expecting for the ...56 id to be removed and only the ...81 id to remain. 56 was removed but to my surprise 81 had been decreased to 80.
const oldIds = [
10032789416531456
];
const newIds = [
10032789435529381,
10032789416531456
];
const result = newIds.filter(newId => !oldIds.some(oldId => oldId === newId));
console.log(result)
//Expected result is: [10032789435529381], instead I get [10032789435529380]
I was able to solve this problem by using strings for ids instead of numbers.
If you type 10032789435529381 in the js console, it returns 10032789435529380. You've exceeded the capacity of the javascript integer, causing it to be treated as a less precise floating point number.
This is part of the reason why using strings for IDs instead of numbers is typically recommended.

Javascript split number and string and keep both [duplicate]

This question already has answers here:
Javascript and regex: split string and keep the separator
(11 answers)
Splitting a string into chunks by numeric or alpha character with JavaScript
(3 answers)
Closed 6 years ago.
I have a string
var houseNumber = '13a';
I want to split the addition from the number so I can keep it in a other field.
How can I split this value without losing the number or the addition? At the end I would like to have 2 fields with the following type:
var houseNumber = 13; //Number
var addition = 'a'; //String
There are many questions about this, but I can't find one where both values has to be saved. That's why I created a new question.
Use the following code
var string_a = "jkjkhj89898";
var x = string_a.match(/[^\d]+|\d+/g);
console.log(x)
working fiddle.
Thanks

How can I convert my string to a number in Javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert String variable to int in javascript?
I have the following:
var dataElapsed = $("#stats-list").attr("data-elapsed");
This creates a string called dataElapsed but I expect a number. How can I convert this?
Is there some way to convert with JQuery? or do I have to use some Javascript way?
Try this(assuming the data attributes have valid numeric values):
var dataElapsed = parseFloat($("#stats-list").attr("data-elapsed")); //for decimal.
or
var dataElapsed = parseInt($("#stats-list").attr("data-elapsed"), 10); //for integer.
You can use the .data() method to get values from data attributes
var dataElapsed = $("#stats-list").data("elapsed");

Categories

Resources