Access value from a string object - Javascript - 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.

Related

Sending a String concatenated with variable raises an error in Minecraft

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' });

How to send an array of objects inside form data in React JS?

I have been trying to send an array of objects inside a form data using React JS at the backend. When I am pushing the data inside form data using its append method, it is showing my array as this
SurveyAnswers: [object object, object, object]
in browsers network tab but we have been receiving null at the backend. We have checked the backend API it is working fine when we are sending data using postman, But, when data is being sent through frontend, it is having a problem. Following is my code snippet:
const answers = [
{
Answer: "Hello World",
QuestionId: 26,
UserId: 190
},
{
Answer: "Document",
File: file,
UserId: 190,
QuestionId: 23
}
]
const onSubmit = () => {
const data = new FormData();
data.append("SurveyAnswers", answers);
const res = await executeAddSurveyFormAnswers({ data: data });
console.log('response, res);
}
If you're trying to pass an object, you will need to "stringify" the object
data.append("SurveyAnswers", JSON.stringify(answers))
Then on the backend, you will need to "Parse" or "Deserialize" the string to convert back to an object. I don't know what language you are using for server side, but you can do a search for "parse json string in XXX" <-XXX is the language (ie.. C#)
Then on the backend, you will need to "Parse" or "Deserialize" the string to convert back to an object.
If you're using Node.js, you'd use JSON.parse() in order to deserialize the stringified object to a native javascript object.

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"}

convert mongodb object to javascript object

I pass a config file to another node.js module when starting it. The config file contain the following json:
"resolution": {
"activated": true,
"types": [
{"of": 23}
]
}
When I print the received types array in the called node.js module, it looks like
console.log('types array: '+ this.config.resolution.types)
//output
types array: [object Object]
if I tried to print the text by using JSON.stringify(), I get the following result
[{"of":23}]
My problem start when I try to replace the types array with a list retried from a mongodb database. my code looks like:
"resolution": {
"activated": true,
"types": [
savedTypes
]
}
Now when I print the received types config, it looks like this:
types array: { _id: 5ab9fe8fd1f64303cd98f122, of: 23, __v: 0 }
and the called node module is not working properly with this config. How can I cast this to an object? I tried to use
JSON.parse(savedTypes)
and get the error
SyntaxError: Unexpected token _ in JSON at position 2
If you use mongoose, I think that the correct form is using ToJSON() function.
Otherwise, you can use JSON.parse(JSON.stringify(data)); But I think that de first form is better.
=)
Alternatively you could use .toObject() method from javascript to convert mongoose object into javascript object.
Here is a reference link to dig out more
https://alexanderzeitler.com/articles/mongoose-tojson-toobject-transform-with-subdocuments/

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