removing the backslashes in json string using the javascript - 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.

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

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

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()).

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");

try to get the value of json object

I have an ajaxpost that returns a response in form of json and I want to show the message
{ "TEXT" : "Please fix it. there might be otehr reason, and need to address it, or call, incorrect username/password-username/port?. " }
How can I get the value of json? I used the following but Message is undefined, What are the other ways of getting json object
var TEXT = text.resp;
Include this library and below code to parse your json
var json = $.parseJSON(obj.responseText);
var msg = json.message;
You can also try below code
var json = JSON.parse(obj.responseText);
var msg = json.message;
You should try to parse the object and then access it with json["object"] instead of the dot.

JSON invalid character error

when json is sent from the VB.net it sends it as text. When I inspect the data parameter in the ajax success I see data = [{'PageInformation':'test'}]
But in the following I get invalid character error --WHY?
var dataObj = jQuery.parseJSON(data);
Use double quotes: data = [{"PageInformation":"test"}]

Categories

Resources