I'm working on a project and I need to send simple requests from a Python backend to a JavaScript App. I have a simple array with names ["x", "y", "z"] and I send it serialized over the socket but when I receive it I don't know how to parse it in a simple array format, not JSON format.
The code should be something like this
websocket.onmessage = function(event){
const receivedMessage = someParses.deserialize(format, event.data);
console.log(receivedMessage);
}
``
JSON.parse is for both JSON & array
for example
inputOfJsonString ='{"age":12,"name":"Mrx"}'
JSON.parse(inputOfJsonString)
=> {age: 12, name: "Mrx"}
anotherInputOfArrayString ="[12,13]"
JSON.parse(anotherInputOfArrayString)
=> [12,13]
Can you post the sample serialize string you are receiving in event.data as the serialization techniques in JS may very you can use
JSON.parse( string, modifierfunction )
and depending upon the response you receive can apply a modifier function
I used json.dumps() to format the array in python and it works now. Thanks
Related
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.
I am calling a REST API in my project for creating some records.
Everything is working fine but I got a challenge, the JSON request body is too big (having thousands of keys and values).
Now I want to compress the request body. I tried it using JavaScript
var reqJSON = { ... } // too big JSON object
var compressedJSON = JSON.stringify(reqJSON, null, 0); // converting JSON to String (compression)
Now I am sending the string in the request body and converting this string into JSON at the server-side.
I am curious, is it the correct way of JSON compression? If yes how can I check the difference in the request body size?
Thanks for your time.
That isn't compression at all.
var reqJSON = { ... } // too big JSON object
That will give you a JavaScript object, not JSON. Possibly your Ajax library will convert it to JSON if you pass it. There's no way for us to know. If the data is to get to the server then it will need serializing to some format that can be sent over the wire so something must be converting it before the HTTP request is made.
var compressedJSON = JSON.stringify(reqJSON, null, 0); // converting JSON to String (compression)
That will give you JSON. There's no compression involved though.
If you want to compress it then you'd need to look for a library that can do actual compression.
You can use gzip for compress json its working fine
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.
I'm getting a json response from the forecast.io api with
JSON.parse(open("https://api.forecast.io/forecast/api-key/latitude,longitude").read)
And it looks like this
{"latitude"=>58.5942,
"longitude"=>16.1826,
"timezone"=>"Europe/Stockholm",
"offset"=>2,
"currently"=>{
"time"=>1367829429,
"summary"=>"Clear",
"icon"=>"clear-day",
"precipIntensity"=>0,
"temperature"=>59.04,
"dewPoint"=>41.6,
"windSpeed"=>11.49,
"windBearing"=>224,
"cloudCover"=>0.08,
"humidity"=>0.53,
"pressure"=>1022.88,
"visibility"=>6.21,
"ozone"=>319.4
}
I'm new to json but this is not regular json right? What should I do to get this to my view in script tags?
Thanks.
Use the particular JSON Keymap you want in the call, and return it in the JSON request callback function. I believe that would resolve your problem.
response = HTTParty.get('https://api.forecast.io/forecast/api-key/latitude,longitude', {:timeout => 3})
#currenttemp = response["temp"]
it will return in a json object because it detects it is JSON. (HTTParty is just a helper gem)
I am sending the following response from server :
return new OperationResult.Created { CreatedResourceUrl = getURI(newDuplicateKfEntity), ResponseResource = newDuplicateKfEntity };
My question is how can I get this CreatedResourceUrl object in my javascript??
Instead of OperationResult.Created return a typed DTO and use a Codec to encode it as Json. After that consuming Json in JavaScript is simple.