String to JSON parse issue with number conversion - javascript

Hi Here I am using JavaScript to convert string to Json object,Here below my code
const json = '{"result":true, "count":42,"groupID": 80000000000000809}';
const obj = JSON.parse(json);
console.log(obj);
result is
Object { result: true, count: 42, groupID: 80000000000000820 }
but required output is
{ result: true, count: 42, groupID: 80000000000000809 }
Why the groupID value is changing during the conversion.Please help me to resolve this.
Thanks for your response.
I have found solution for this.
const json = '{"result":true, "count":42,"groupID": 80000000000000000809}';
const obj = JSON.parse(json.replace(/("[^"]*"\s*:\s*)(\d{17,})/g, '$1"$2"'));
console.log(obj);
The above code I have used string replace method to replace big-integer into string.

The integer you are trying to parse is too large. JavaScript only supports up to 53-bit integers, so the maximum value for a Number type in JavaScript is +/- 9,007,199,254,740,991. Any larger and you'll need to use a BigInt. See here for how to work with large integers in JavaScript.
I would recommend changing groupID in your API response to a string rather than an integer.
If you can't do this, then you could also try using a JSON parsing library that can handle BigInt types, e.g. json-bigint.

You can always check Number.MAX_SAFE_INTEGER(). Let's compare this result with the number you're working with:
9007199254740991
80000000000000826
Your number appears to be over the technical maximum that JavaScript supports with integers. I tested with a few other numbers, they appear to have similar problems. Documentation...
The Number.MAX_SAFE_INTEGER constant represents the maximum safe integer in JavaScript (253 - 1).
For larger integers, consider using BigInt. (Source: MDN Web Docs: Number.MAX_SAFE_INTEGER
You can always use a string, though, since it is likely that you'll actually be getting this JSON from a web-server, rather than locally defined:
const json = '{"result":true, "count":42,"groupID": "80000000000000809"}';
const obj = JSON.parse(json);
console.log(obj);

Related

How get maximum from array of string using node js?

I'm trying to get maximum value from the array of string using node JS.
I have enabled CDC on SQL server, I can get transaction-id of data in the string(converted from binary to string within SQL server itself), after that I'm getting an array of strings like below(I'm just posting array string that's being collected from array of objects)
arr1= [ '0x000001B1000000900009',
'0x000001B1000000900009',
'0x000001B1000000900009',
'0x000001B1000000900009']
If get max from array using the following code
Math.max.apply(Math, arrayofobject.map(function(o) { return o.y; }))
I get the below output
122441614897446930
it automatically converts string to a number and get max,
I don't want this way, I want max from the array of string, becasue I need to update nextOffset for CDC.
Thanks in advance
You mean
const arr1 = ['0x000001B1000000900016',
'0x000001B1000000900007',
'0x000001B1000000900008',
'0x000001B1000000900009'
]
console.log(arr1.sort().pop())

How to convert a Buffer to an array of ints node.js

I have a c# application that converts a double array to a byte array of data to a node.js server which is converted to a Buffer (as convention seems to recommend). I want to convert this buffer into an array of the numbers originally stored in the double array, I've had a look at other questions but they either aren't applicable or just don't work ([...buf], Array.prototype.slice.call(buf, 0) etc.).
Essentially I have a var buf which contains the data, I want this to be an array of integers, is there any way I can do this?
Thank you.
First, you need to know WHAT numbers are in the array. I'll assume they are 32bit integers. So first, create encapsulating Typed Array around the buffer:
// #type {ArrayBuffer}
var myBuffer = // get the bufffer from C#
// Interprets byte array as 32 bit int array
var myTypedArray = new Int32Array(myBuffer);
// And if you really want standard JS array:
var normalArray = [];
// Push all numbers from buffer to Array
normalArray.push.apply(normalArray, myTypedArray);
Note that stuff might get more complicated if the C#'s array is in Big Endian, but I assume it's not. According to this answer, you should be fine.
I managed to do this with a DataView and used that to iterate over the buffer, something I'd tried before but for some reason didn't work but does now.

Data-attribute retrieval and parsing javascript

I am new to javascript programming and i am stuck with data-attribute retrieval.
The below link is a bit useful for people using jQuery
store and retrieve javascript arrays into and from HTML5 data attributes
I would like to do the same with vanilla js. With the help of custom data-attributes i would like to create objects & array.
<div id="getAnimation"
data-r="564"
data-c="96"
data-custom="x:0;y:0;z:0;rotationX:0;rotationY:0;rotationZ:0;scaleX:0.75;scaleY:0.75; skewX:0;skewY:0;opacity:0;transformPerspective:600;transformOrigin:50% 50%;"
data-s="700"
data-st="1400"
</div>
Do HTML5 custom data attributes “work” in IE 6?
The above link helps in getting data attributes very well but how can be filter the string in data-custom or straight create an object of data-custom.
If someone know a library to do this please let me know
Here are a couple quick functions which will let you store, retrieve and delete any JSON-able data to a data attribute
function setData(node, data_name, data_value) {
node.dataset[data_name] = JSON.stringify(data_value);
}
function getData(node, data_name) {
return JSON.parse(node.dataset[data_name]);
}
function delData(node, data_name) {
return delete node.dataset[data_name];
}
Then to write an Array to #getAnimation in data-fizz
// variables to use
var elm = document.getElementById('getAnimation'),
foo = [1, 2, 3, 'a', 'b', 'c'];
// store it
setData(elm, 'fizz', foo);
// retrieve it
var bar = getData(elm, 'fizz');
// look what we have
console.log(bar); // [1, 2, 3, "a", "b", "c"]
Requires IE 11+ because I use node.dataset, if you change this to the methods node.setAttribute, node.getAttribute and node.removeAttribute as used, the requirement drops to IE 8+ because of the JSON.stringify and JSON.parse
That particular example is quite straight forward: It's a series of name:value pairs separated with semicolons. So you can get an array of the pairs using split, and then get the name and valid separate using split again. If you want to create properties on an object using those names and values, you can do that with bracketed notation:
// Get the value
var val = theElement.getAttribute("data-custom");
// Split it into fields on `;` (with optional whitespace on either side)
var fields = val.split(/\s*;\s*/);
// Create a blank object
var obj = {};
// Loop through the fields, creating object properties:
fields.forEach(function(field) {
// Split the field on :, again with optional whitespace either side
var parts = field.split(/\s*:\s*/);
// Create a property on the object using the name, and assigning the value
obj[parts[0]] = parts[1];
});
I'm using String#split there, giving it a regular expression to tell it where the split up the string.
In the resulting object, with just the code above, the property values will all be strings. For instance, obj.scaleX will be the string "0.75". If you need them as numbers, you can convert them to numbers in any of several ways:
parseFloat, which will convert as many characters as it can but ignore trailing characters. so parseFloat("0.75foo") is 0.75, not an error.
Number, which will not be tolerant like parseFloat, Number("0.75foo") is NaN, not 0.75.
Applying any mathematical operator, the unary + is common: +"0.75" is 0.75.
So rather than just grabbing the values as strings, we could check to see if they look like they might be numbers and convert them if so:
// Loop through the fields, creating object properties:
fields.forEach(function(field) {
// Split the field on :, again with optional whitespace either side
var parts = field.split(/\s*:\s*/);
// Does the value look like a number?
if (/(?:^\d+$)|(?:^\d+\.\d+$)/.test(parts[1])) {
// Yes
obj[parts[0]] = +parts[1];
}
else {
// No
obj[parts[0]] = parts[1];
}
});
That assumes . as the decimal separator, and assumes there won't be a thousands separator.
Side note: Above I've used Array#forEach, which is an ES5 feature not present on older browsers. forEach can be "shimmed" on older browsers, though. You can see all sorts of ways of looping through arrays in this answer here on SO.

Convert any data to array buffer in JavaScript

I'm not sure if I understand the concept of UInt8Array right, but I'm trying to convert any given data which can be image/png,jpg,gif text/html,json,js,css,less or any type of data including octet binary and then I can create data type UInt8Array
So, for any given data how can I convert them so I can make this possible?
var value = new Uint8Array([2, 4, 6, 8]);
Obviously that numbers in the array is hardcoded with random numbers, but the idea I think I want that part to be the data that I'm trying to convert to.
If you can get the data in a Base64 string MDN can help with this.
To sum up, use base64DecToArr
var myArray = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw=="); // "Base 64 \u2014 Mozilla Developer Network"
var myBuffer = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw==").buffer; // "Base 64 \u2014 Mozilla Developer Network"
alert(myBuffer.byteLength);

$.inArray is giving -1?

This should be pretty straight forward:
HTML
my link
<input type="hidden" id="pageids" value="28,27,26,17,18,19,">
Jquery
var thumbaid = $('#thumba').data("id");
// get position
var itemids = $('#pageids').val();
var itemids_array = itemids.split(',');
var currentpos = $.inArray(thumbaid, itemids_array );
alert(currentpos);
Gives me -1?
The funny thing is that if I replace " $(thumba).data("id")" for a number in the jquery code as "26", it works!
The result should be, in this case, "2".
Any ideas?
You need to convert the value to a string.
var thumbaid = $('#thumba').data("id").toString();
Why...? If you were to
console.log(itemids_array);
you would see this
["28", "27", "26", "17", "18", "19", ""]
They are not numbers, they are strings. See http://api.jquery.com/data/
That is because the thumbaid is a number, and the itemids_array contains strings. Try var currentpos = $.inArray(thumbaid.toString(), itemids_array );
jQuery's data function reads the data- attributes and parses digits to numbers.
jQuery's data function does things to the data it reads from the data-* attributes on initialization, including turning number-like strings into numbers. Since $.inArray does an === check, that's why it fails. You end up looking for the number 26 in an array of strings.
If you simply use .attr("data-id") instead, the conversion won't happen.
This behavior is documented in the data docs:
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.
If you're only using data to read data-* attributes, I recommend using attr instead to avoid this kind of thing, and to avoid the confusion caused by the fact that while data initializes from data-* attributes, it doesn't write to them when you set data. Of course, if you need to store data associated with elements and you don't want it on an attribute (because it's not string data, or you don't want it showing in the DOM inspector), data is the right tool for that job.
The reason its not working, is because jQuery data is returning an int not string.
See this example.
my link
<input type="hidden" id="pageids" value="28,27,26,17,18,19,">
Javascript:
var thumbaid = $('#thumba').data('id').toString();
// get position
var itemids = $('#pageids').val();
var itemids_array = itemids.split(',');
console.log(itemids_array);
var currentpos = $.inArray(thumbaid, itemids_array );
console.log(currentpos);
$().data() will convert the data-* attribute's value to a JavaScript value. In your case, thumbaid is converted to a number.
$.inArray compares elements using the strict equality operator(===). That is, '26' === 26 returns false as no type coercion occurs.
From the jQuery.data() docs:
Every attempt is made to convert the string to a JavaScript value
(this includes booleans, numbers, objects, arrays, and null). A value
is only converted to a number if doing so doesn't change the value's
representation. For example, "1E02" and "100.000" are equivalent as
numbers (numeric value 100) but converting them would alter their
representation so they are left as strings. The string value "100" is
converted to the number 100.

Categories