Heyo, I want to get a data from a json file but it says undefined.
This is my json file:
[
{
"channel": [
"960229917264584736"
],
"info": {
"cooldown": 3000
}
},
{
"channel": [
"960229880405053473"
],
"info": {
"cooldown": 6000
}
}
]
And here is how i'm trying to get it:
let channels = JSON.parse(fs.readFileSync("./channels.json"));
console.log(channels.channel)
Thanks for helping^^
The error in the code comes down to the wrong mapping in JavaScript.
Note that in JavaScript code, channels corresponds to a JSON array with multiple channels, like this:
let channels = [{channel1}, {channel2}] // the file JSON is an array [{},{}]
So to access a channel you will need to go to the following path:
channels[0].channel // 0 can be replaced for any valid index number
// output: {"channel": ["960229917264584736"],"info": {"cooldown": 3000}}
To get a channel id:
channels[0].channel[0]
// output: "960229917264584736"
Related
I am in no way an expert with groovy so please don't hold that against me.
I have JSON that looks like this:
{
"metrics": [
{
"name": "metric_a",
"help": "This tracks your A stuff.",
"type": "GAUGE",
"labels": [
"pool"
],
"unit": "",
"aggregates": [],
"meta": [
{
"category": "CAT A",
"deployment": "environment-a"
}
],
"additional_notes": "Some stuff (potentially)"
},
...
]
...
}
I'm using it as a source for automated documentation of all the metrics. So, I'm iterating through it in various ways to get the information I need. So far so good, I'm most of the way there. The problem is this all needs to be organized per the deployment environment. Meaning, multiple metrics will share the same value for deployment.
My thought was I could create a map with deployment as the key and the metric name for any metric that has a matching deployment as the value. Once I have that map, it should be easy for me to organize things the way they should be. I can't figure out how to do that. The result is all the metric names are added which is expected since I'm not doing anything to filter them out. I was thinking that groupBy would make sense here but I can't figure out how to use it effectively and frankly I'm not sure it will solve my problem by itself. Here is my code so far:
parentChild = [:]
children = []
metrics.each { metric ->
def metricName = metric.name
def depName = metric.meta.findResult{ it.deployment }
children.add(metricName)
parentChild.put(depName, children)
}
What is the best way to create a new map where the values for each key are based off a specific condition?
EDIT: The desired result would be each key in the resulting map would be a unique deployment value from all the metrics (as a string). Each value would be name of each metric that contains that deployment (as an array).
[environment-a:
[metric_a,metric_b,metric_c,...],
environment-b:
[metric_d,metric_e,metric_f,...]
...]
I would use a combo of withDefault() to pre-fill each map-entry value with a fresh TreeSet-instance (sorted no-duplicates set) and standard inject().
I reduced your sample data to the bare minimum and added some new nodes:
import groovy.json.*
String input = '''\
{
"metrics": [
{
"name": "metric_a",
"meta": [
{
"deployment": "environment-a"
}
]
},
{
"name": "metric_b",
"meta": [
{
"deployment": "environment-a"
}
]
},
{
"name": "metric_c",
"meta": [
{
"deployment": "environment-a"
},
{
"deployment": "environment-b"
}
]
},
{
"name": "metric_d",
"meta": [
{
"deployment": "environment-b"
}
]
}
]
}'''
def json = new JsonSlurper().parseText input
def groupedByDeployment = json.metrics.inject( [:].withDefault{ new TreeSet() } ){ res, metric ->
metric.meta.each{ res[ it.deployment ] << metric.name }
res
}
assert groupedByDeployment.toString() == '[environment-a:[metric_a, metric_b, metric_c], environment-b:[metric_c, metric_d]]'
If your metrics.meta array is supposed to have a single value, you can simplify the code by replacing the line:
metric.meta.each{ res[ it.deployment ] << metric.name }
with
res[ metric.meta.first().deployment ] << metric.name
I am using Perspective API (you can check out at: http://perspectiveapi.com/) for my discord application. I am sending an analyze request and api returning this:
{
"attributeScores": {
"TOXICITY": {
"spanScores": [
{
"begin": 0,
"end": 22,
"score": {
"value": 0.9345592,
"type": "PROBABILITY"
}
}
],
"summaryScore": {
"value": 0.9345592,
"type": "PROBABILITY"
}
}
},
"languages": [
"en"
],
"detectedLanguages": [
"en"
]
}
I need to get "value" in "summaryScore" as an integer. I searched it on Google, but i just found reading value for not categorized or only 1 times categorized json files. How can i do that?
Note: Sorry if i asked something really easy or if i slaughtered english. My primary language is not english and i am not much experienced on node.js
First you must make sure the object you have recived is presived by nodeJS as a JSON object, look at this answer for how first. After the object is stored as a JSON object you can do the following:
Reading from nested objects or arrays is as easy as doing this:
object.attributeScores.TOXICITY.summaryScore.value
If you look closer to the object and its structure you can see that the root object (the first {}) contains 3 values: "attributeScores", "languages" and "detectedLanguages".
The field you are looking for exists inside the "summeryScore" object that exists inside the "TOXICITY" object and so on. Thus you need to traverse the object structure until you get to the value you need.
I have the following JSON object r2,
[
{
"reserva_id":"200",
"estancias":[
{
"reserva_estancia":"266",
"huespedes":[
{
"reserva_huesped":"272",
"reserva_estancia":"266",
"numero_huesped":"1",
"huesped":"123",
"huesped_nombre":"dos dos, dos",
"rfid":null
},
{
"reserva_huesped":"276",
"reserva_estancia":"266",
"numero_huesped":"2",
"huesped":"183",
"huesped_nombre":"MUESTRA MUESTRA, CARMEN",
"rfid":null
}
]
}
]
},
{
"reserva_id":"201",
"estancias":[
{
"huespedes":[
{
"reserva_huesped":"273",
"reserva_estancia":"267",
"numero_huesped":"1",
"huesped":"148",
"huesped_nombre":"MUESTRA MUESTRA, CARMEN",
"rfid":null
},
{
"reserva_huesped":"277",
"reserva_estancia":"267",
"numero_huesped":"2",
"huesped":"187",
"huesped_nombre":"TEST TEST, TESTCIVITFUN",
"rfid":null
}
]
}
]
}
]
I am trying to get the first huesped for each reservation, and for that I am using the following script, to create a list called profiles and store profileId's:
def profiles = jsonpath(r2,'$..[:].estancias[:].huespedes[0].huesped')
The output should be the following:
[
"123",
"148"
]
However, when I print profiles.text I get all the content of the estancias object, instead of just the huesped number.
When using Jayway's JSONPath like this I get the desired oputput:
$..[*].estancias[*].huespedes[0].huesped
You can try the path expression with your JSON here online.
I want to format a JSON object in my Nodejs server. Delete some fields, rename some fields, and move some fields.
I have many different schemas need to apply to many different JSON, so I hope has a lib that can parse a configuration file and to it.
Maybe a configuration file like this:
DELETE request.logid
DELETE request.data.*.time
MOVE request.data.images data.images
And a JSON before applies an above schema:
{
"request": {
"data": {
"book": {
"name": "Hello World",
"time": 1546269044490
},
"images": [
"a-book.jpg"
]
},
"logid": "a514-afe1f0a2ac02_DCSix"
}
}
After applied:
{
"request": {
"data": {
"book": {
"name": "Hello World"
}
}
},
"data": {
"images": [
"a-book.jpg"
]
}
}
Where is the lib it is?
I know that write a function can do the same thing directly, but the problem is I have too many different schemas and too many different JSON, so I wanna manage them by configuration file rather than a js function.
Yes you could do something like this...
// Note: psuedocode
// Read the configuration file;
const commands = (await readFile('config')).split('\r\n').split(' ');
// your original JSON;
const obj = {...};
// Modify the JSON given the commands
commands.forEach( row=>{
if(row[0]==="DELETE"){
delete obj[row[1]];
}else if(row[0]==="MOVE"){
// use lodash to make your life easier.
_.set(obj,`${row[2]}`,_.get(obj,`${row[1]}`));
delete obj[row[1]];
}else if(...){
...
}
})
I have a json data like:
{
"cse_thumbnail": [
{
"width": "188",
"height": "268",
"src": "http://abc.dk"
}
],
"metatags": [
{
"referrer": "origin-when-cross-origin",
"og:image": "http://def.dk"
}
],
"cse_image": [
{
"src": "http://ghi.dk"
}
]
}
There are 3 array lists coming in the JSON. I want to check if the corresponding keys are existing when I'm getting the response:
cse_thumbnail
metatags
cse_image
I'm tried all the key:value pair check in python like (hasattr, key in list etc) which are not working at all.
Please help to get it resolved.
You can use in to check if a key is present
import json
with open('data.json') as thing:
data = json.load(thing)
keys = ('cse_thumbnail', 'metatags', 'cse_image')
for key in keys:
print(key in data)