Sending a String concatenated with variable raises an error in Minecraft - javascript

Okay, so, I'm having trouble sending players strings combined with variables. For example, this line of code:
client.write("chat", { message: ("Username:"+data.data[0]["name"].toString())})
This data variable is a JSON object. Printing out
"Username:"+data.data[0]["name"].toString()
Works without an error, but when I try send it to the client, the client disconnects with this error message:
Internal Exception: io.netty.handler.codec.DecoderException:
com.google.gson.JsonSyntaxException:
com.google.gson.stream.MalformedJsonException: Use
JsonReader.setLenient(true) to accept malformed JSON at line 1 column 10
BTW, I'm using npm minecraft-protocol javascript

I just checked the documentation and the sent message doesn't correspond to the format that should be used.
The json should NOT be in json direclty, but should be stringified. So, such as the usage said, you should use something like that:
var msg = {
translate: 'chat.type.announcement',
"with": [
'Username',
data.data[0]["name"]
]
};
client.write("chat", { message: JSON.stringify(msg), position: 0, sender: '0' });

Related

Access value from a string object - Javascript

Not sure why I am not able to access the keys from a string object
data looks like this
I am getting this data from a python variable
const data = '{regression: {success: 7310, total: 14154, failed: 4665, unstable: 2104, aborted: 75}, stable: {success: 2699, total: 4252, failed: 462, unstable: 15, aborted: 1076}, patch: {success: 2824, total: 5494, failed: 2518, unstable: 39, aborted: 113}}'
I need to extract the keys regression, stable, patch and eventually the details of how many test cases were in success, total, failed etc.
Tried to change the string to object using JSON.parse(data) but it gives error as its not an object.
How can I extract the keys and value in this case
There is an easy approach to make this work.
In your Python code, use the json.dumps() method to convert a Python dictionary into valid JSON, like below.
import json
dictonary = {
"name": "Name",
"age": 0
};
print(json.dumps(dictionary)) # Returns JSON
Then, in your JavaScript, add the following code.
const data = "{\"name\": \"Name\", \"age\": 0}";
console.log(JSON.parse(data)); // Returns a JavaScript object
The JavaScript code should now return a JavaScript object without any errors.

AWS Lambda: How do I get property inside event.body, it keep return undefined

I was trying to get event.body.data, but it keep return me undefined, i tried JSON.parse(event), JSON.parse(event.body), JSON.parse(event.body.data), JSON.stringify, almost tried out things that i can do with JSON and non of them seems to work. When i tried JSON.parse(event), will give syntax error. So i suspect it already in JSON object format and when i console.log it, it didn't have the " " quote. If it is already in JSON format, why can't I access the property in it. I also tried wrap it inside if(event.body.data) and it doesn't work as well. Anyone know how to get property inside event.body?
Based on your screenshot it looks like the body data is a JSON string. That means you have to parse it first before you can use it. Something like this:
exports.handler = function(event, context, callback) {
const body = JSON.parse(event.body)
console.log('data: ', body.data)
}
Then apply the suggestions from #Marcin and fix your JSON data because it's missing quotes.
Your even.body is invalid json string, which explain why JSON.parse fails. Thus, you should check who/what is making the request and modify the code of the client side to invoke your API with a valid json string.
It should be:
'{"action": "message, "data": "black clolor"}'
not
"{action: 'message, data: 'black clolor'}"
Thanks #Marcin for the feedback, it was indeed caused by invalid json string sent from frontend.
Changing it to the code below solved the issue.
{"action": "message", "data": "black clolor"}

how to solve problem getting json object element

I have a json object that i want to use.
{
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkOTQ3OTg4N2RlMGRkMDc4ZjEzM2FmNyIsImVtYWlsIjoiYWxzb25nZHVuc3RhbjJAZ21haWwuY29tIiwicm9sZSI6IkNVU1RPTUVSIiwiaWF0IjoxNTcwMDI3MDA4fQ.FcpoBPmhTSX535bNgE2ezCCWsNFPjEhc87hM4y6WadM"
}
so when i try to access it using
console.log("Postback: " + payload.type)
but i get an error of
Postback: undefined
i have looked over some resources on the web and most of them do it this way and it works but i am not sure why mine is not giving the value for type
thanks in advance
Subh is right. You have to parse the JSON into an object before accessing type using payload.type syntax.
So, let's say you have the following:
let payload = {
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzWadM"
}
You have to convert it into a JS object using JSON.parse:
let payloadObj = JSON.parse(payload);
Now, if you do payloadObj.type, you should be fine.
console.log(payloadObj.type); // PROVIDER_PAYLOAD
It should work fine.
UPDATE: ERROR: SyntaxError: Unexpected token a in JSON at position 0
If you are getting this error, try following to Parse the payload.
let payloadObj = JSON.parse(JSON.stringify(payload))
It should solve the problem for you.

Issue with JSON.parse , don't know why is not parsing everything

I'm developing a web app with Node.js using Sails framework(based on Express) and i'm using a third party image solution called Transloadit (no need to know Transloadit).
Anyway, that's not the problem, i'm been able to implement the Transloadit form and receive the information from their API.
My problem is that, Transloadit gives me the response as a String, and I need to access the response objects, so i'm using var objRes = JSON.parse(req.body.transloadit); to parse it to an JSON object, and when I console.log(objRes); the object is not correctly parsed, i get this: (see all JSON here https://gist.github.com/kevinblanco/9631085 )
{
a bunch of fields here .....
last_seq: 2,
results: {
thumb: [
[
Object
]
]
}
}
And I need the data from the thumb array, my question is, Why is doing that when parsing ?
Here's the entire request req.body object: https://gist.github.com/kevinblanco/9628156 as you can see the transloadit field is a string, and I need the data from some of their fields.
Thanks in advance.
There is nothing wrong with the parsing of the JSON -- in fact there is no problem at all.
consol.log limits the depth of what it is printing which is why you are seeing [object] in the output.
If you want to see the full output in node.js then just use the inspect utility like this;
console.log(util.inspect( yourobject, {depth:null} ));
and that will print the entire content.
Note that this is just an artifact of console.log printing it.

Result of BsonDocument.ToJson fails when used in JSON.parse

I'm retrieving data from MongoDB and then sending it to client:
var bsonDocument = ... retrieve from database ...
var dto = new Dto { MyBson = bsonDocument.ToJson() };
On the client I'm trying to parse MyBson property using JSON.parse.
I'm getting the following error: SyntaxError: Unexpected token N. I guess this is because one of the properties looks like this:
{ ..., "SomeIntProp" : NumberLong(70) }
JavaScript parser simply doesn't understand Bson data type: NumberLong.
How should I convert BsonDocument to JSON so that the output would omit NumberLong?
There is no easy way to solve this, I worked out a solution by writing my own parsing function which understands the MongoDB BSON types and does the conversion. The native JSON.parse only understands the types used by the JavaScript. Here is my version:
https://gist.github.com/Hrish2006/8270187
You probably will not need the html snippets in the code.

Categories