JSON string assignment not working - javascript

What is wrong with my code below? I am passing to this function a JSON string but the assignment ends up blank. I can see the string in FireBug in the function parameter so I know it arrives at the function, but it does not make it past the assignment (as in the assignment is "undefined"). I want to pull from the string the wty_upgrade array. I am using some of the code I received help with in this question. Thanks
JSON string (as I see it in FireBug:
{"wty_upgrade":[
{"wty":"Upgrade from 3 to 5 years", "mth":24, "pig":3000},
{"wty":"Upgrade from 3 to 10 years", "mth":84, "pig":8000}
]}
Function Call:
LoadWtyUpgPlans('3', JSON)
function LoadWtyUpgPlans(StdWty, UpgWty) {
var WtyRow = '';
var WtyUpgrades = UpgWty.wty_upgrade; <--- here the assignment is blank/undefined
STUFF HERE...
};

you can use as a this example may be useful fir you,
var jsn = '{"wty_upgrade":[
{"wty":"Upgrade from 3 to 5 years", "mth":24, "pig":3000},
{"wty":"Upgrade from 3 to 10 years", "mth":84, "pig":8000}]}';
//OR you can parse then use
jsonres = JSON.parse(jsn);

Related

Javascript JSON.stringify method removes trailing zero if object has value as x.0 ( like 6.0 ) [duplicate]

I am working on a project where I require to format incoming numbers in the following way:
###.###
However I noticed some results I didn't expect.
The following works in the sense that I don't get an error:
console.log(07);
// or in my case:
console.log(007);
Of course, it will not retain the '00' in the value itself, since that value is effectively 7.
The same goes for the following:
console.log(7.0);
// or in my case:
console.log(7.000);
JavaScript understands what I am doing, but in the end the actual value will be 7, which can be proven with the following:
const leadingValue = 007;
const trailingValue = 7.00;
console.log(leadingValue, trailingValue); // both are exactly 7
But what I find curious is the following: the moment I combine these two I get a syntax error:
// but not this:
console.log(007.000);
1) Can someone explain why this isn't working?
I'm trying to find a solution to store numbers/floats with the exact precision without using string.
2) Is there any way in JS/NodeJS or even TypeScript to do this without using strings?
What I currently want to do is to receive the input, scan for the format and store that as a separate property and then parse the incoming value since parseInt('007.000') does work. And when the user wants to get this value return it back to the user... in a string.. unfortunately.
1) 007.000 is a syntax error because 007 is an octal integer literal, to which you're then appending a floating point part. (Try console.log(010). This prints 8.)
2) Here's how you can achieve your formatting using Intl.NumberFormat...
var myformat = new Intl.NumberFormat('en-US', {
minimumIntegerDigits: 3,
minimumFractionDigits: 3
});
console.log(myformat.format(7)); // prints 007.000
Hi
You can use an aproach that uses string funtions .split .padStart and .padEnd
Search on MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
Here you have an example:
const x = 12.1;
function formatNumber( unformatedNumber) {
const desiredDecimalPad = 3;
const desiredNonDecimalPad = 3;
const unformatedNumberString = unformatedNumber.toString();
const unformatedNumberArr = unformatedNumberString.split('.');
const decimalStartPadded = unformatedNumberArr[0].padStart(desiredDecimalPad, '0');
const nonDecimalEndPadded = unformatedNumberArr[1].padEnd(desiredNonDecimalPad, '0');
const formatedNumberString = decimalStartPadded + '.' + nonDecimalEndPadded;
return formatedNumberString;
}
console.log(formatNumber(x))

Why is Google Scripts' JSON.parse method converting numbers to floats?

I'm writing a Google Script code to manage some data in Google Sheet. I'm pulling data from external API and every time I receive numbers in JSON response they're converted to floats by JSON.parse available in Google Script.
Example:
const test = '{ "numericValue": 0 }';
JSON.parse(test)
Result: {numericValue=0.0}
const test = '{ "stringValue": "0" }';
JSON.parse(test)
Result: {stringValue=0}
It doesn't happen with browser JSON.parse method.
Is there any way to fix this besides converting all numbers to strings before parsing?
The logger has always done that. But the console doesn't. Don't know the issue but you get use to it. Don't worry about it
function floatTest() {
const obj='{"value": 0 }';
console.log(JSON.parse(obj));
Logger.log(JSON.parse(obj));
}
Execution log
8:28:00 AM Notice Execution started
8:28:00 AM Info { value: 0 }
8:28:00 AM Info {value=0.0}
8:28:01 AM Notice Execution completed
a simple way to verify that what you are saying is wrong:
const test_1 = JSON.parse( '{ "val": 0 }')
console.log ('test_1', typeof test_1.val, Number.isInteger(test_1.val) , test_1.val )
const test_2 = JSON.parse( '{ "val": "0" }')
console.log ('test_2', typeof test_2.val, Number.isInteger(test_2.val) , test_2.val )

easy way to multiply a value to successive substrings in javascript

Good morning, sorry for my poor English.
I'm a neophyte and I'm trying to create a javascript program that, given a string in input, if it finds inside defined substrings it returns a value to each substring and returns the sum of the values ​​found as output. Everything ok here. But I'm finding it difficult to manage the case where in front of the substring that I'm looking for, there's for example "2x" which means that the value of the next substring (or of all subsequent substring) is to be multiplied for 2. How can I write in simple code this exception?
Example:
A1 = 1
M1 = 1
input description = A1-M1
output = 2
input descritpion = 2 x A1-M1
output = 4
Thanks in advance
For more comprehesion, you can find my code below:
let str_description = "2 x A1-M1";
var time_mont = [];
var time_cloa = [];
if(str_description.includes("A1")){
time_mont.push (0.62);
} else {
time_mont.push (0);
}
if(str_description.includes("M1")){
time_mont.push (0.6);
} else {
time_mont.push (0);
}
How can I manage "2 x " subtring?

Groovy render as JSON java.sql.timestamp in In JavaScript milliseconds not displayed

I have a java.util.ArrayList which contains the red marked value:
if I render it with render relations as JSON then in JavaScript the value is the following:
The milliseconds are gone, if I understand it right the value of receiveDate is a string so there is no way to parse it to another format.
Is there a way to render the value that the milliseconds are not gone ?
Method 1
import grails.converters.JSON
def r = [now: new Date(), name: 'Roong']
JSON.registerObjectMarshaller(Date) {o -> o.getTime()}
println(r as JSON)
Result 1
{
"now": 1356595418027,
"name": "Roong"
}
or you can set in Config.groovy
Method 2
grails.converters.json.date = "javascript"
Result 2
{
"now": new Date(1356595418027),
"name": "Roong"
}
You can save the missing part to another key-value pair, using method
java.sql.Timestamp.getNanos()
and restore the complete value in javascript by consolidating the two parts. For example:
String receiveDate = grails.converters.JSON.parse(jsonData).data[0].receiveDate
def formatDate = receiveDate.replace('Z','.'+ dt.getNanos().toString()).replace('T', ' ')
def tsDate = java.sql.Timestamp.valueOf(formatDate)
println 'The timestamp is : ' + tsDate

Regular Expression: pull part from string. with JS

Hey all im not every good with regexp i was hoping someone could help.
ok so this is the sting "KEY FOUND! [ 57:09:91:40:32:11:00:77:16:80:34:40:91 ]"
And i need to pull "57:09:91:40:32:11:00:77:16:80:34:40:91", now this key can be meany length not just as written here and with or with out the ":"
now the second sting i would like to test and extract is: "[00:00:09] Tested 853 keys (got 179387 IVs)", i would like to pull "00:00:09" and "853" and "179387".
this would be the raw string http://regexr.com?31pcu or http://pastebin.com/eRbnwqn7
this is what im doing now.
var pass = new RegExp('KEY FOUND\!')
var tested = new RegExp('Tested')
var fail = new RegExp('\Failed. Next try with ([0-9]+) IVs')
var data="Look at the link i added"
if (tested.test(data)) {
self.emit('update', mac, {
'keys' : data.split('Tested ')[1].split(' keys ')[0],
'ivs' : data.split('got ')[1].split(' IVs')[0]
});
} else if (pass.test(data)) {
var key = data.split('KEY FOUND! [')[1].split(' ]')[0].split(':').join('');
} else if (fail.test(data)) {
console.log(data);
}
thanks all
Edit:
I have added more the the question to help with the answer
If it is always surrounded by [] then it is simple:
\[([\s\S]*)\]
This will match any characters enclosed by [].
See it in action here.

Categories

Resources