How to print JSON element having comma in key? - node.js

Here, I have a JSON object like
var Obj = { id: 'xx', 'xlink:href': 'http://www.example.com' }
Now, I can print id by
console.log(Obj.id);
But I am not able to get url by doing like this,
console.log(Obj.xlink:href);
It gives me error like,
SyntaxError: missing ) after argument list
Question is here, How can I print data of a key, having comma in between?

Use bracket notation
Obj["xlink:href"]
More info here

The dot notation in JavaScript is only useful when the key is suitable as a token.
Otherwise, you should use the bracket notation.
Here, Obj['xlink:href'] will return the value you want.

As others have said in their answer, you should try following
console.log(Obj['xlink:href']);

Related

NodeJS why is object[0] returning '{' instead of the first property from this json object?

So I have to go through a bunch of code to get some data from an iframe. the iframe has a lot of data but in there is an object called '_name'. the first key of name is 'extension_id' and its value is a big long string. the json object is enclosed in apostrophes. I have tried removing the apostrophes but still instead of 'extension_id_output' I get a single curly bracket. the json object looks something like this
Frame {
...
...
_name: '{"extension_id":"a big huge string that I need"} "a bunch of other stuff":"this is a valid json object as confirmed by jsonlint", "globalOptions":{"crev":"1.2.50"}}}'
}
it's a whole big ugly paragraph but I really just need the extension_id. so this is the code I'm currently using after attempt 100 or whatever.
var frames = await page.frames();
// I'm using puppeteer for this part but I don't think that's relevant overall.
var thing = frames[1]._name;
console.log(frames[1])
// console.log(thing)
thing.replace(/'/g, '"')
// this is to remove the apostrophes from the outside of the object. I thought that would change things before. it does not. still outputs a single {
JSON.parse(thing)
console.log(thing[0])
instead of getting a big huge string that I need or whatever is written in extension_id. I get a {. that's it. I think that is because the whole object starts with a curly bracket. this is confirmed to me because console.log(thing[2]) prints e. so what's going on? jsonlint says this is a valid json object but maybe it's just a big string and I should be doing some kind of split to grab whaat's between the first : and the first ,. I'm really not sure.
For two reasons:
object[0] doesn't return the value an object's "first property", it returns the value of the property with the name "0", if any (there probably isn't in your object); and
Because it's JSON, and when you're dealing with JSON in JavaScript code, you are by definition dealing with a string. (More here.) If you want to deal with the object that the JSON describes, parse it.
Here's an example of parsing it and getting the value of the extension_id property from it:
const parsed = JSON.parse(frames[1]._name);
console.log(parsed.extension_id); // The ID

JSON Object Property Missing Quotation Marks?

I have a very trivial problem, and I'm having trouble finding similar questions. On my Node JS server, I prepare an object of key-value pairs. The keys that have spaces in them are converted to strings like this {'key':'value'}. However, the keys without spaces or special characters don't have quotes surrounding them. When I print it out it looks like this {key:'value'}. The problem is, when I send the response back to the client, the keys without surrounding quotes are missing from the object. So how would I surround all the keys with quotes then so that it is sent properly?
JSON Objects must follow the RFC-7159, the easiest way to get a RFC-compliant JSON object is to use JSON.stringify on the object you want to output on your server side, which is natively supported in NodeJS.
You just need to convert the response to client by converting the javascript object to JSON object.
var object = { key: 'value' };
var newObject = JSON.stringify(object);
console.log("format : ", newObject);
//the JSON.stringify() function definition, it will simply turn the object log into a JSON string.
OUTPUT:
format : '{ 'key' : 'value' }'

nodejs skipping single quote from json key in output

I see a very weird problem when json when used in nodejs, it is skipping single quote from revision key . I want to pass this json as input to node request module and since single quote is missing from 'revision' key so it is not taking as valid json input. Could someone help how to retain it so that I can use it. I have tried multiple attempts but not able to get it correct.
What did I try ?
console.log(jsondata)
jsondata = {
'splits': {
'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
Expected :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
But in actual output single quote is missing from revision key :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
revision: 'master'
}
}
Run 2 :- Tried below code this also produce same thing.
data = JSON.stringify(jsondata)
result = JSON.parse(data)
console.log(result)
Run 3:- Used another way to achieve it
jsondata = {}
temp = {}
splits = []
temp['revision'] = 'master',
temp['os-name'] = 'ubuntu'
temp['platform-version'] = 'os'
temp['traffic-percent'] = 100
splits.push(temp)
jsondata['splits'] = splits
console.log(jsondata)
Run 4: tries replacing single quotes to double quotes
Run 5 : Change the order of revision line
This is what is supposed to happen. The quotes are kept only if the object key it’s not a valid JavaScript identifier. In your example, the 'splits' & 'revision' don't have a dash in their name, so they are the only ones with the quotes removed.
You shouldn't receive any error using this object - if you do, update this post mentioning the scenario and the error.
You should note that JSON and JavaScript are not the same things.
JSON is a format where all keys and values are surrounded by double quotes ("key" and "value"). A JSON string is produced by JSON.stringify, and is required by JSON.parse.
A JavaScript object has very similar syntax to the JSON file format, but is more flexible - the values can be surrounded by double quotes or single quotes, and the keys can have no quotes at all as long as they are valid JavaScript identifiers. If the keys have spaces, dashes, or other non-valid characters, then they need to be surrounded by single quotes or double quotes.
If you need your string to be valid JSON, generate it with JSON.stringify. If it's OK for it to be just valid JavaScript, then it's already fine - it does not matter whether the quotes are there or not.
If, for some reason, you need some imaginary third option (perhaps you are interacting with an API where someone has written their own custom string parser, and they are demanding that all keys are surrounded by single quotes?) you will probably need to write your own little string generator.

How to replace the Hexadecimal values to its original character string in C?

I have correlated the Token value taken from the following response snippet:
result.sessionToken = '7AFF3BA8\x2DD913\x2D4211\x2D990E\x2D7DF3AB5687B7';
Using the web_reg_save_param function as:
web_reg_save_param(
"TOKEN",
"LB=result.sessionToken = '",
"RB=';",
"ORD=1",LAST);
But in a later request I need to send the correlated value in the below format:
7AFF3BA8-DD913-4211-990E-7DF3AB5687B7
The value \x2D is to be substituted by -.
I am right now using the below 'C' and LR code for this:
strcat(pstr1,lr_eval_string("{RToken}"));
strcat(aSeparator,"\\");
for(a=0,b=0;pstr1[a]!=NULL;a++,b++)
{
if(pstr1[a]==aSeparator[0])
{
strcat(pstr2,"-");
pstr2[b+1]=pstr1[a+4];
a=a+5;
b=b+2;
}
pstr2[b]=pstr1[a];
}
lr_save_string(lr_eval_string(pstr2), "sessionToken");
I wanted a generic and another approach for this problem. I don't want to use web_convert_param function, but if there is a hidden trick to convert the string as desired I would like to know.
Thanks,
Ritika
Try This...lr_save_string(lr_eval_string("{TOKEN}"),"convertedtkn");

What do empty square brackets after a variable name mean in Groovy?

I'm fairly new to groovy, looking at some existing code, and I see this:
def timestamp = event.timestamp[]
I don't understand what the empty square brackets are doing on this line. Note that the timestamp being def'd here should receive a long value.
In this code, event is defined somewhere else in our huge code base, so I'm not sure what it is. I thought it was a map, but when I wrote some separate test code using this notation on a map, the square brackets result in an empty value being assigned to timestamp. In the code above, however, the brackets are necessary to get correct (non-null) values.
Some quick Googling didn't help much (hard to search on "[]").
EDIT: Turns out event and event.timestamp are both zero.core.groovysupport.GCAccessor objects, and as the answer below says, the [] must be calling getAt() on these objects and returning a value (in this case, a long).
The square brackets will invoke the underlying getAt(Object) method of that object, so that line is probably invoking that one.
I made a small script:
class A {
def getAt(p) {
println "getAt: $p"
p
}
}
def a = new A()
b = a[]
println b.getClass()
And it returned the value passed as a parameter. In this case, an ArrayList. Maybe that timestamp object has some metaprogramming on it. What does def timestamp contains after running the code?
Also check your groovy version.
Empty list, found this. Somewhat related/possibly helpful question here.
Not at a computer, but that looks like it's calling the method event.timestamp and passing an empty list as a parameter.
The same as:
def timestamp = event.timestamp( [] )

Resources