Node JS String Inside Curly Brackets - javascript

// My input String
// Could be on : true, on : false, bri : 255, etc, etc
var inputString = 'on : true'
console.log(inputString);
var wrongResult = { inputString }
console.log(wrongResult);
// The result that I am trying to achieve
var desiredResult = {
on : true
}
console.log(desiredResult);
Run it: https://repl.it/LCDt/4
I created the above code snippet to demonstrate the problem that I am experiencing. I have an input string that I receive that could be "on : true", "on : false", "bri : 250", "sat : 13", etc. When posting this data to a server, the format that works is seen above as the "desireResult".
But, when taking a string, such as 'on : true', in a variable, and placing it inside {}, it always seems to create a dictionary with the variable name as the key and the string itself as the value.
Can someone explain why this is and how to get around it?

Can someone explain why this is
Because the syntax { foo } means "Create an object, give it a property called foo, give that property the value of the foo variable.
how to get around it
Parse the data. Assign it explicitly.
Start by splitting the string on :. Then remove the white space. Then test is the second value is a number or a keyword. And so on.
This would be easier if the data you were receiving was in a standard format. Then you could use an existing parser. If you have control over the input: Change it to be valid JSON and then use JSON.parse.

You could use JSON.parse for that but you need to feed him valid JSON.
You need to have an string in form of:
{"on":true}
using JSON.parse('{"on":true}') will return you the desired object.

Related

constructing object with key value and value accepting space in js

I might be wrong , but curious to know whether can i construct an object with key value pair, with value accepting space only
Somehow after parsing i need to get as
properties:
name:
value: //accepting space
let property = { name: {'value':} }; //currently its giving me error like expression expected
I need to give something like this , is it possible in js or in react
Any help will be highly appreciated
You can create objects with undefined or null values, like this:
let property = {
name: undefined,
value: undefined
}
let null_property = {
name: null,
value: null
}
which is the closest you can get to 'empty space' in Javascript, if you mean what I think you mean.
You can't, however, not assign anything at all in your syntax because Javascript requires that something be assigned to every single variable. You can test this by noting that:
let thing;
and
let thing = undefined;
are the EXACT same line of code from your computer's perspective. The first is simply a convenient shorthand way to write the second.

Is there a function to find an expression and return the element ahead?

Good morning,
I would like to know if there is a specific function in javascript, which extracts from the message below only the value "141", after identifying the term "Temperatura.SaidaATM".
{ "d" : { "Temperature.ATM Output" : [141]
**Edit: The above package comes from sub MQTT in Json format.
The complete package is this below:
{"d":{"Temperature.ATM Output":[141]},"ts":"2021-12-18T13:28:34.964579"}
However I need to treat it to extract only the information between brackets "[xxx]", in the example above it is "141" but this value varies.
But I also need the quoted reference "Temperature.OutputATM".
Summing up:
1- The message "{"d":{"Temperature.OutputATM":[xxx]}"ts":"2021-12-18T13:28:34.964579"}" is received.
2- I need to extract the xxx from a javascript code
3- When reading "Temperatura.SaidaATM" in the message, return only what is in square brackets right after "[xxx]"
4- Final message return: xxx
Thank you in advance!
Yes. You have an object and you can select by key like that:
data = { "d" : { "Temperature.ATM Output" : [141] }}
console.log(data.d["Temperature.ATM Output"][0])

Reference Nested JavaScript Object

I have this code:
var string = {
nameString : "nameValue",
nameString2 : "nameValue2",
nameString3 : "nameValue3",
datathing : 0,
};
var data = {
data : 1,
dataNum2 : 2,
dataNum3 : 3,
dataNum4 : 4,
};
var thing = {
datathing1 : 10,
datathing2 : 20,
datathing3 : 30,
datathing4 : 40,
};
var object = {
object1 : string,
data1 : data,
thing1 : thing,
};
Why do neither of these means to access the data work:
alert("testReference= " + object['object1']['string']['nameString']);
alert("testReference= " + object.object1.string.nameString);
I cannot understand it, even though similar examples found below and textbooks state explicitly that they should work:
Accessing nested JavaScript objects with string key
Thanks in advance for any input!
I am currently constructing an object and passing it around, a 'for in' will bring up the values but a 'typeof' test or any other way I try and access will not work, either I will encounter an error (which breaks the program, I think) or I get 'undefined'....
One last thing if this gets solved, is it ok to nest a key that is the same name value as its parent, such as data.data - this leads to the possibility of further nesting such as data.data.data...
Let's look at what's wrong with each example, then take a look at the way that works right.
Example 1
object['object1']['string']['nameString']
We expect object['object1'] to return the object string, right? So lets simplify the big expression by replacing that part of it. That'll make it easier for us to understand.
So now we have string['string']['nameString'].
But string has no member called 'string', so string['string'] returns undefined.
And when you try to treat undefined as an object, you get an error!
Example 2
object.object1.string.nameString
We expect object.object1 returns the object string, right? So lets simplify the big expression by replacing that part of it. That'll make it easier for us to understand.
So now we have string.string.nameString.
But string has no member called 'string', so string.string returns undefined.
And when you try to treat undefined as an object, you get an error!.
What You Want
object.object1.nameString (or object['object1']['nameString'])
We expect object.object1 returns the object string, right? So lets simplify the big expression by replacing that part of it. That'll make it easier for us to understand.
So now we have string.nameString, and we expect that to return "nameValue".
And it does!

JSON object creation error

I am trying to create a JSON object in the particular format
{ "id": 12234 , "name": "Alex" , "gender": "Male"}
// My code starts here
var number = userid; // alert(userid) is 12345
var name= nameuser; // alert(nameuser) is Alex
var g= gender; // alert(gender) is male
var userObj = { "id": number , "name": name , "gender":g}
I tried `JSON.stringify(userObj); ,
that returns the object type as
{"id":"12345" , "name":"Alex" , "gender":"Male"}
but this is not what I want as I want the number to be 12345 and not "12345".
also tried stringifying the fields inside the object like
{ "id": number , "name":JSON.stringify(name) ,gender: JSON.stringify(g)}
but when I do alert(userObj) my object type is Object object and this is not a format the server recognises.
I am sure there is a workaround for this but I am unable to figure one out
JSON works with strings exclusively. It's invalid to have anything other than a string, array, or other JSON object in JSON. That said, a "number" is not allowed; it needs to be a string. Whatever you are working with with the JSON later needs to be able to change the string back it to a number, if necessary. JavaScript usually does a good job of coercing these.
On the server side you can just do something like
obj = json_decode(source)
obj.id = (int)obj.id
I think that your solution will come down to what you want to DO with the JSON, rather than how you want it to be formatted.
If you're using it in other JavaScript code, then the JSON.parse method is going to take care of most of your issue on the other side (with automatic type-casting dealing with the rest).
If you're using it on the server-side, again, PHP or similar will decode the object appropriately.
And if it's a more-strict language on your server, all you need to do is remember which parameters need to be cast to boolean or to int/float.
The below code from your question is valid JSON.
{ "id": 12234 , "name": "Alex" , "gender": "Male"}
I am guessing that the problem you have is that your userid variable is a string, not a number. If so, try
var number = parseInt(userid, 10);
(The 10 parameter indicates that you are using base 10 numbers as opposed to something like binary or hex).
store the object type as one of the property and use it to convert the way you want.

How to retrieve value from object in JavaScript

Hi I am using a Java script variable
var parameter = $(this).find('#[id$=hfUrl]').val();
This value return to parameter now
"{'objType':'100','objID':'226','prevVoting':'" // THIS VALUE RETURN BY
$(this).find('[$id=hfurl]').val();
I want to store objType value in new:
var OBJECTTYPE = //WHAT SHOULD I WRITE so OBJECTTYPE contain 400
I am trying
OBJECTTYPE = parameter.objType; // but it's not working...
What should I do?
Try using parameter['objType'].
Just a note: your code snippet doesn't look right, but I guess you just posted it wrong.
Ok, not sure if I am correct but lets see:
You say you are storing {'objType':'100','objID':'226','prevVoting':' as string in a hidden field. The string is not a correct JSON string. It should look like this:
{"objType":100,"objID":226,"prevVoting":""}
You have to use double-quotes for strings inside a JSON object. For more information, see http://json.org/
Now, I think with $(this).find('[$id=hfurl]'); you want to retrieve that value. It looks like you are trying to find an element with ID hfurl,but $id is not a valid HTML attribute. This seems like very wrong jQuery to me. Try this instead:
var parameter = $('#hfurl').val();
parameter will contain a JSON string, so you have to parse it before you can access the values:
parameter = $.parseJSON(parameter);
Then you should be able to access the data with parameter.objType.
Update:
I would not store "broken" JSON in the field. Store the string similar to the one I shoed above and if you want to add values you can do it after parsing like so:
parameter.vote = vote;
parameter.myvote = vote;
It is less error prone.

Categories

Resources