PAHO mqtt client(mqttws31.js) and JSON.parse() does not work - javascript

I am publishing simple JSON string {"TMP":"-15.5826"} to the web client. Message appears in message.payloadString I can print it to in html but I could not parse the message with JSON.parse(). obj and data is undefined..this is the main problem, to solve this I used JSON.stringify() first, this time message parsed but data is still undefined. It seems stringify adds extra double quotes and invalidates json string. mqttws31.js is the latest, broker is mosquitto 1.4.4. What should I do to get JSON.parse() working?
publishing is through mosquitto command:mosquitto_pub -t /main/SENSOR -m {"TMP":"-15.5826"}
function onMessageArrived(message) {
var topic = message.destinationName;
var payload = message.payloadString;
$('#ws').prepend('<li class=messagelist>' + topic + ' = ' + payload + '</li>');
var jsonString = JSON.stringify(payload);
obj = JSON.parse(jsonString); //parse with extra double quotes
//obj = JSON.parse(payload); //does not parse
var data = obj.TMP;
alert(data);
};

You need to prevent your shell from removing the double quotes during publishing, by using single quotes around the JSON string:
mosquitto_pub -t /main/SENSOR -m '{"TMP":"-15.5826"}'
When that's done, you can use JSON.parse(payload) (no need for JSON.stringify()).

Related

Unable to parse a valid JSON

My api sends back a JSON response like this using PHP Silex:
{"response":true,"message":"Bla","userId":"AAA"}
But i can't parse it in my Typescript frontend
this.authService.login(body).then((result : any) => {
console.log(result.data); // => {"response":true,"message":"Bla","userId":"AAA"}
let parsed = JSON.parse(result.data);
console.log(parsed.message); // => throws "SyntaxError: Unexpected token in JSON at position 0\n at JSON.parse (<anonymous>)
My php endpoint using PHP and Silex Framework:
$app->post('/user/login', function (Request $request) use ($app, $config) {
$email = $request->request->get('user-email');
$password = $request->request->get('user-password');
$rsp = loginUser($email,$password);
return $app->json($rsp);
});
When try and hardcode the json object into code, it does parse!
UPDATE SOLUTION
I had to use trim() for result.data to remove whitespaces, somehome the response came with whitespaces and JSON didn't like that. Thank you all for your help.
SOLUTION
i used result.data.trim() for it to work, somehow the response had whitespaces and JSON didn't like that.
You may have a \u0000 char somewhere coming from your PHP code.
Try to remove these characters from your JSON string as soon as you get it from PHP:
this.authService.login(body).then((result : any) => {
string = result.data.replace("\u0000", "");
string = string.replace("\\u0000", "");
let parsed = JSON.parse(string);

Golang backend to javascript JSON Parse

I am using the gorilla websocket library for golang: http://www.gorillatoolkit.org/pkg/websocket
This is the code I am using to create the websocket connection:
conn, err := upgrader.Upgrade(w, r, nil)
Having an issue with sending JSON from golang to javascript. I can get it working but have to do what seem to be unnecessary steps. Here is the basics of the golang backend that does not work:
type clientDB struct{
ChunksWritten int64
ChunksRead int64
BytesWritten int64
BytesRead int64
DataBytesWritten int64
DataBytesRead int64
ActivePeers int
TotalPeers int
TorrentHashString string
}
fullClientDB := new(clientDB) //creating a new clientDB struct
b, err := json.Marshal(fullClientDB)
if err != nil {
fmt.Println(err)
return
}
conn.WriteJSON(b)
When I use JSON.parse in javascript I get the following response:
var clientUpdate = JSON.parse(evt.data);
eyJDaHVua3NXcml0dGVuIjowLCJDaHVua3NSZWFkIjowLCJCeXRlc1dyaXR0ZW4iOjU0NDgxLCJCeXRlc1JlYWQiOjc4NzgyLCJEYXRhQnl0ZXNXcml0dGVuIjowLCJEYXRhQnl0ZXNSZWFkIjowLCJBY3RpdmVQZWVycyI6MCwiVG90YWxQZWVycyI6NDMsIlRvcnJlbnRIYXNoU3RyaW5nIjoiOWY5MTY1ZDlhMjgxYTliOGU3ODJjZDUxNzZiYmNjODI1NmZkMTg3MSJ9
I can get it working making the following changes:
conn.WriteJSON(string(b))
Then in javascript I actually parse the data TWICE.
var clientUpdate = JSON.parse(evt.data);
var clientUpdateJSON = JSON.parse(clientUpdate);
After that I can access the data correctly as a JSON object. Is there something I'm missing about sending JSON objects from golang to javascript over websockets?
The gorilla websocket package automatically encodes to JSON so using the standard library to encode as well was just encoding it twice, causing it to show up as base64.
Thanks guys!

removing the backslashes in json string using the javascript

i have JSON response which is having backslashes and some responses are not containing the backslashes.
I need to show error message based on the response, How do i parse the JSON response using javascript?
JSON response with out backslashes,
{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}
response with backslashes,
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"}
i tried in the following way but it is working only for JSON response which is not having the backslashes.
var strj = JSON.stringify(err._body);
var errorobjs = strj.replace(/\\/g, "");
Actually the problem is not with / slashs. The JSON is INVALID.
remove these " from backend server
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal
Server
Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal
Server Error"}
double quote before "{"timestamp and one after login"}"
these two highlighted and your code will work.
var data = '{"_body":{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"},"status":500,"ok":false,"statusText":"Internal Server Error"}';
var json_data = JSON.parse(data);
console.log(json_data);
You are actually wrapping body object in string at backend which is not valid.
"body" : "bodyOBJ" //Invalid
"body" : bodyObj //Valid
var obj = JSON.parse(response)
if(typeof obj._body == "string") {
obj._body = JSON.parse(obj._body)
}
console.log(obj);
Solution:
var response = {"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"};
var body = JSON.parse(response._body);
console.log(body.error);
Explanation:
You have a top level object with one key, _body. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. Unless you are able to fix the server side code, you have to decode the nested JSON manually.

How to send getJSON a string with special characters?

I want to send a getJSON with special characters?
In this case i have a .js file which create the string to send using getJSON methos. for that i use following command.
$.getJSON(strUrl, UI_DesignPecTab.validateResponse);
Using above method i need to send a string like follows :
var ID = "W6"
var headerString = "PT##?" + ID + "Z##;#TKT/#CHK/#BOR/";
But when i send this to server side it fails due to this uri contains some invalid characters? I need to know how can i get this done. I have tried to encode and send this using "encodeURIComponent()" but um not sure is it correct or not? if it correct how to decode it server side in java? For the above method i have used following code:
headString = URLDecoder.decode(pecTabData.getHeadString(), "UTF-8");

Problems loading JSON code in Python

I've been tyring to figure out how to load JSON objects in Python.
I'm able to send a JSON string to the server, but there it fails.
This is what I'm sending through a websocket with JavaScript:
ws.send('{"test":"test"}');
The server receives it without a problem, but can't validate it:
{"test":"test"}
This is not a JSON object!
Which comes forth from this code:
try:
data = data[:-1]
json.loads(data)
except ValueError:
print 'This is not a JSON object!'
else:
print ('JSON found!')
The data = data[:-1] is there to strip the delimiter sent through the websocket.
import traceback
try:
d = json.loads(data[data.index('{'):-1])
except:
traceback.print_exc()
else:
print(d)
This way only the dictionary part of the data-string is parsed to json.loads().

Categories

Resources