How can I get the multiple subchild objects from json using nodejs? - node.js

I am trying to fetch the specifice object from my json files. For now I can fetch any tag instead of the "p" tag from it. you can please have look at the screenshot I have attached.
Click to open the json file
this is how I'm trying to fetch p tag:
'use strict';
const fs = require('fs');
var data = JSON.parse(fs.readFileSync('./me.json'));
data.Document.Decision.forEach(x => {
console.log(x.Texte_Integral.p);
});

This is a weird way of organizing your block, I recommend rewriting/reorganizing the JSON so it is more easily accessible.
There are a few things you have to know before this answer makes sense:
Array indexes
[] resembles an array, you can access each index by doing array[index], for example:
let arr = ['zero', 'one', 'two'];
console.log(arr[0]); //expected output: 'zero'
Bracket Notation
In JavaScript, there are two ways to access a variable's value, either by dot notation or bracket notation. As far as I know, the only differences these have are just the ability to use dynamic input and characters you can't usually use inside a variable's name, for example:
let obj = {
var1: "this is variable1",
var2: {
var3: "this is variable3 inside variable2"
}
}
console.log(obj.var1) //expected output: "this is variable1"
console.log(obj[`var1`]) // expected output: "this is variable1"
console.log(obj.var2.var3) //expected output: "this is variable3 inside variable2"
console.log(obj[`var2`].var3) // expected output: "this is variable3 inside variable2"
console.log(obj[`var2`]["var3"]) // expected output: "this is variable3 inside variable2"
Bracket notation also works inside objects, thus why the variable names inside as a string, like "Document", works.
let obj2 = {
"var1": 1,
["var2"]: 2,
var3: 3
};
console.log(obj2["var1"]) // expected output: 1
// console.log(obj2"var1") is INVALID and does not work
console.log(obj2["var2"]) // expected output: 2
console.log(obj2.var3) // expected output: 3
Coming to the solution
data.Document.Decision.forEach(x => {
console.log(x.Texte_Integral[0].p)
});
This returns ["ASDFDSFDSFSD"], if we wanted to use it as a string and not an array (remember the brackets) then we would access the first index of the array. This would be done by adding [0] at the end.
❕ Solution
data.Document.Decision.forEach(x => {
console.log(x.Texte_Integral[0].p[0])
});
Future Information
About stackoverflow, next time, please share code via code blocks and not screenshots. Thank you for coming to ask your question, we just want it to be easier for us to both understand and access the code! I had to type the whole thing out myself, which could've been easily avoided by just copy/paste-ing the code. If you don't know how to do certain things in the textbox, see the formatting help page.

Related

Reading an Array correctly

I have a json file called "GuideDB" which contains data about somethings.
GuildDB.json
{"GuideID":{"prefix":"","DJ":null,"Roles":""}}
Basically I want to access the data "Roles" in a way I can manage each element in that line, e.g.:
const myArray = GuildDB.Roles; //GuildDB.Roles is the only way to access that line.
myArray.forEach(element => {
console.log("<#&" + element + ">")
});
this code gives the error "forEach", because the array is not correctly formated.
How do I add Items in GuildDB.Roles?
client.database.guild.set(message.guild.id, {
prefix: GuildDB.prefix,
DJ: GuildDB.DJ,
Roles: GuildDB.Roles + ", " + createdRole.id, //Bug: First run always writes the comma first.
});
This will result the following:
{"GuideID":{"prefix":"","DJ":null,"Roles":", 123, 1234, 12345, 123456"}}
Which is not what I want.. and I don't care how this looks, I need to make it easy access to read/manage that data of Roles.
Hope anyone can help..
You can do something like this to convert Roles into array first and then use forEach loop on it.
const myArray = GuildDB.Roles.split(",");

Weird backticks string behavior in ES6 [duplicate]

I'm not sure how to explain this, but when I run
console.log`1`
In google chrome, I get output like
console.log`1`
VM12380:2 ["1", raw: Array[1]]
Why is the backtick calling the log function, and why is it making a index of raw: Array[1]?
Question brought up in the JS room by Catgocat, but no answers made sense besides something about templating strings that didn't really fit why this is happening.
It is called Tagged Template in ES-6 more could be read about them Here, funny I found the link in the starred section of the very chat.
But the relevant part of the code is below (you can basically create a filtered sort).
function tag(strings, ...values) {
assert(strings[0] === 'a');
assert(strings[1] === 'b');
assert(values[0] === 42);
return 'whatever';
}
tag `a${ 42 }b` // "whatever"
Basically, its merely tagging the "1" with console.log function, as it would do with any other function. The tagging functions accept parsed values of template strings and the values separately upon which further tasks can be performed.
Babel transpiles the above code to
var _taggedTemplateLiteralLoose = function (strings, raw) { strings.raw = raw; return strings; };
console.log(_taggedTemplateLiteralLoose(["1"], ["1"]));
As you can see it in the example above, after being transpiled by babel, the tagging function (console.log) is being passed the return value of the following es6->5 transpiled code.
_taggedTemplateLiteralLoose( ["1"], ["1"] );
The return value of this function is passed to console.log which will then print the array.
Tagged template literal:
The following syntax:
function`your template ${foo}`;
Is called the tagged template literal.
The function which is called as a tagged template literal receives the its arguments in the following manner:
function taggedTemplate(strings, arg1, arg2, arg3, arg4) {
console.log(strings);
console.log(arg1, arg2, arg3, arg4);
}
taggedTemplate`a${1}b${2}c${3}`;
The first argument is an array of all the individual string characters
The remaining argument correspond with the values of the variables which we receive via string interpolation. Notice in the example that there is no value for arg4 (because there are only 3 times string interpolation) and thus undefined is logged when we try to log arg4
Using the rest parameter syntax:
If we don't know beforehand how many times string interpolation will take place in the template string it is often useful to use the rest parameter syntax. This syntax stores the remaining arguments which the function receives into an array. For example:
function taggedTemplate(strings, ...rest) {
console.log(rest);
}
taggedTemplate `a${1}b${2}c${3}`;
taggedTemplate `a${1}b${2}c${3}d${4}`;
Late to the party but, TBH, none of the answers give an explanation to 50% of the original question ("why the raw: Array[1]")
1. Why is it possible to call the function without parenthesis, using backticks?
console.log`1`
As others have pointed out, this is called Tagged Template (more details also here).
Using this syntax, the function will receive the following arguments:
First argument: an array containing the different parts of the string that are not expressions.
Rest of arguments: each of the values that are being interpolated (ie. those which are expressions).
Basically, the following are 'almost' equivalent:
// Tagged Template
fn`My uncle ${uncleName} is ${uncleAge} years old!`
// function call
fn(["My uncle ", " is ", " years old!"], uncleName, uncleAge);
(see point 2. to understand why they're not exactly the same)
2. Why the ["1", raw: Array[1]] ???
The array being passed as the first argument contains a property raw, wich allows accessing the raw strings as they were entered (without processing escape sequences).
Example use case:
let fileName = "asdf";
fn`In the folder C:\Documents\Foo, create a new file ${fileName}`
function fn(a, ...rest) {
console.log(a); //In the folder C:DocumentsFoo, create a new file
console.log(a.raw); //In the folder C:\Documents\Foo, create a new file
}
What, an array with a property ??? ???
Yes, since JavaScript arrays are actually objects, they can store properties.
Example:
const arr = [1, 2, 3];
arr.property = "value";
console.log(arr); //[1, 2, 3, property: "value"]

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

How to extract values from this complex Puppet Struct

I have this data structure in puppet:
Struct[
'ssh_keys' => Hash[
String,
Struct[
'path' => String,
'content' => String,
]
]
] $myStructure
And I would like to extract all the 'path' values into an Array.
I got as far as mapping the inner Struct using
$testvariable = $myStructure['ssh_keys'].map |$items| { $items[1] }
But a bit suck here, any help would be much appreciated.
It's not clear what you're hung up on, as you are indeed most of the way to a solution that should work. For hashes, however, I do usually prefer the form of the map() function in which the lambda takes two parameters, a separate key and value. That will read more clearly in this case:
$testvariable = $myStructure['ssh_keys'].map |$unused, $ssh_key| { $ssh_key['path'] }
But you should also be able in your original code to index $items[1] as the hash (Struct) it is: $items[1]['path'].
You could also use the dig() function if you cannot abide the mixture of array and hash indexing in the above: $items.dig(1, 'path').

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");

Resources