I'm trying to get data from a json file with snekfetch for my discord bot but I have a problem...
This is a part of the json file
"nodes":{
"main.c10":{
"online":1624,
"inbattles":829
},
If I want to get "online" number I should write this
var c10 = r.body.nodes.main.c10.online;
but with the dot after main is interpreting the request like this:
"nodes":{
"main {
.c10":{
"online":1624,
"inbattles":829
}
},
How I can solve this problem?
You can access that property with square brackets:
var c10 = r.body.nodes['main.c10'].online;
Edit in response to comments:
In this case r.body is a buffer, and so you need to first convert it to an object, only then you can access its properties like .nodes. You can find a working demo here.
JSON.parse(r.body.toString()).nodes['main.c10'].online
Related
I ran into this error while trying to send a pandas to_json object to front end using flask. the codes and errors look like this:
df_higg_msi_scored_manual = pd.read_csv(r'static/CSVFiles/higg_msi_scored_manual.csv')
materials = df_higg_msi_scored_manual.iloc[:33, 3]
material = materials.to_json(orient="values")
return render_template('/impacttool.html', material = material)
var user = JSON.parse('{{brand | tojson | safe}}');
and this is the error that pops up no matter how valid the resulting json file is:
depending on which json i send to the front end, i get either unexpected number or unexpected token, with unexpected token always matching the first alphabet of the first string in json. Could someone please help me figure this out? I've even tried print(material) on flask, then copied the exact json that was printed to the console, assigned that to a variable and sent it to the front end and it worked fine! but for some reason when i do to_json and assign it directly to a variable it throws this error. If someone knows how to fix it I would love to know. Thank you.
In your Javascript try to see what
console.log('{{brand | tojson | safe}}')
gets you because maybe you're trying to turn JSON data into JSON data so maybe also consider removing the | to json part of the variable call
Edit: calling variables doesn't work in files other than HTML files so try parsing the variable directly in the HTML file like so:
<script>
var user = JSON.parse('{{brand | tojson | safe}}')
</script>
or you could add it to a variable in the HTML file then parse it in the javascript file like so:
filename.html:
<script>
var jsondata = '{{brand | tojson | safe}}'
</script>
filename.js
var user = JSON.parse(jsondata)
I found a solution thanks to RaphSinai, it was because the {{ brands | tojson }} was formatted with extra double quotes as "[whatever...]" instead of just the [], so I changed the code from material = materials.to_json(orient="values") to json.loads(material = materials.to_json(orient="values")) and it worked fine.
I'm currently working with a bearer token I need to get some data out of to continue a user journey. I found the following code that does the decoding for me
var jsonData = JSON.parse(responseBody);
const payload = jsonData.Result.AccessToken.split('.')[1]; // Assuming the JWT is in id_token
const parsed = JSON.parse(atob(payload));
It uses atob sandboxed script to decode base 64 encoded payload, when decoded the payload looks a little like this:
{
"http://mytestsite.uk/roles": [
"user"
],
"http://mytestsite.uk/id": "8d2c3de9-4fa2-a58e-68109d977",
"http://mytestsite.uk/email": "tst3#mytestsite.uk",
"sub": "500b416c8942bb0069b98a3c",
"aud": "api.tst.mytestsite.uk",
"iat": 1615544685,
"exp": 1615631085
}
Normally, I would reference the payload body item I want (e.g. sub) like so:
pm.environment.set('sub', parsed.sub);
However, I want to reference "http://mytestsite.uk/id" and am uncertain how to do it.
parsed.http://mytestsite.uk/id
The above causes the script to error and I can't encode it, as that doesn't remove the dots, I obviously can't pass it as a string - I guess I'm unclear on how to correctly pass this name to reference the JSON object correctly.
You should be able to reference it this way:
pm.environment.set('id', parsed['http://mytestsite.uk/id'])
Context :
I'm making a Discord bot using the discord.js library and MongoDB (with mongoose). I created a script that can construct messages from data stored in my MongoDB database. For exemple, if an user on my Discord server type "!hello", it will query my database to construct a reply like "Hello to you!".
I store my reply message data in an document like this :
{
"command": "!hello",
"content": "Hello to you!"
}
(I voluntary omitted some properties here that are useless in the context of my question)
And retrieve it in my code with something like :
let retrievedReply;
await mongo().then(async mongoose => {
try {
let query = {command: message.content};
retrievedReply = await replySchema.findOne(query);
} finally {
mongoose.connection.close();
}
});
message.reply(retrievedReply.content);
My issue :
Now, imagine I want it to respond "Hello username!".
If I didn't construct my reply using data from mongo I could simply do something like :
message.reply(`Hello ${message.member.nickname}!`);
or
message.reply("Hello " + message.member.nickname + "!");
So, in other words, using backticks and ${} syntax or (but I like it less), splitting my string and concatenate my property value like the second example.
The thing is, we can't store a string inside backticks in json format (used by MongoDB). So even if I build my document like so :
{
"command": "hello",
"content": "Hello ${message.member.nickname}!"
}
${message.member.nickname} would not be interpreted like a property value but just like a simple string.
The 1000$ question :
How can I use this property inside my code? I thought about extracting it using regex but it does not change the fact that it will still be a string. Is there a way to "convert" from a string to an usable variable?
EDIT
Since Brettski asked me (rightfully), here is an example of what I want :
message.member.send(`Hello ${message.member}!`);
This message.member property here represent a member object of a Discord guild. It contains a lot of things like its permissions on the guild, its roles, etc.
When we use a member object into a message, Discord will make a mention of the member like bellow.
It works the same with other properties like channels for example. Users can then click on those to see informations about the member or to go directly to the channel, etc. I want to be able to use this.
That is correct you will not be able to store a string literal in Mongo or other way.
One though I had is to put a token in your string and then do a replace on it in message.reply() or before it.
example:
const helloCommand = {
"command": "hello",
"content": "Hello ~~membernickname~~!"
};
In this example the token to replace is ~~membernickname~~
You can use something like this to do the replace:
const command = JSON.parse(helloCommand)
message.member.send(command.content.replace('~~membernickname~~', message.member));
The resulting string being sent to the send() command is the same. So if the nickname is #brettski, the string 'Hello #brettski' will be sent to the send() command.
In your example:
message.reply(`Hello ${message.member.nickname}!`);
the part:
`Hello ${message.member.nickname}!`
is a string literal (template literals). What the function message.reply() ends up getting is 'Hello Nickname' a string. So the replace should work. As a test you can hard code the string used in message.reply() to a known nickname and it should provide the results you expect.
Ok so, #Brettski put me on the right track with the fact that I can use users' or channels' IDs directly as strings within the message and between specific tags.
To reuse the example in my question, I can use this syntax to mention an user :
"<#idOfTheUser>"
What I did is if I want to mention the author of the command in my reply, I put the text in my mongoDB document as so :
const helloCommand = {
"command": "hello",
"content": "Hello $member$!"
};
Then, in my code, I can simply use :
message.reply((retrieveReply.content).replace(/\$member\$/g, `<#${message.member.id}>`))
Of course, I wanted to use more properties so I did a function like :
const messageContentReplace = function(content) {
const replaceableStrings = {
"$member$": `<#${message.member.id}>`,
"$memberName$": message.member.displayName,
"$guild$": message.guild.name
}
return content.replace(/(\$member\$)|(\$memberName\$)|(\$guild\$)/g, match => {
return replaceableStrings[match];
});
(in reality, I did something more complexe because I use an embed message as my response with multiple fields etc... See here about embeds)
I'm making an ajax post request to a super simple python function that takes a student's name and spits out a url that corresponds to it. Currently, the Python function passes this back in json and looks like so when console.log(JSON.stringify(response)) is called:
{"readyState":4,"responseText”:”\ {\”studentURL\”: \”https://prepacademy.jackjohnson.com\”} ”,”responseJSON”: {“studentURL”:”https://prepacademy.jackjohnson.com”},”status":200,"statusText":"OK"}
I was wondering how do I take this larger chunk of information and filter it so that I would only get the https://prepacademy.jackjohnson.com part?
response is a JavaScript Object of which you can access the properties using either Dot-notation or bracket-notation, like so:
let response = {
"readyState": 4,
"responseText": "\ {\"studentURL\": \"https://prepacademy.jackjohnson.com\"} ",
"responseJSON": {
"studentURL": "https://prepacademy.jackjohnson.com"
},
"status": 200,
"statusText": "OK"
};
// dot-notation
console.log(response.responseJSON.studentURL)
// bracket-notation (allows for computed paths)
console.log(response["responseJSON"]["studentURL"])
response.responseJSON.studentURL
I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).