Unable to parse a valid JSON - javascript

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

Related

Laravel Error returns when it does json_decode

I get the data in json format with the help of javascript. The javascript code I wrote actually sends the data in the format I want as follows:
var log_lists = JSON.stringify(Object.assign({}, $scope.log_list));
when I checked it on the internet, I checked that the incoming data is in json format and it was verified by all
When I send the requests, it is received correctly by the controller and when I return, I see the data returned in the console as follows.
My controller code
$log_example = $request->all();
return $log_example;
return data
{
"0":["1","SALES","5,00","REMOVED"],
"1":["2","SALES","10,00","REMOVED"],
"2":["1","BUYER","2","DROPPED"]
}
I use the json_decode function to run it in the foreach loop and when I return the data again I get the error "server error"
return json_decode($log_example, true);
// returns with errors
I couldn't find where I made a mistake.
Thank you for your help and suggestions.
$request->all() return an array by default.
First encode and then decode as below
$log_example = $request->all();
$logs = json_encode($log_example);
$data = json_decode((string) $logs, true);
return $data;

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.

json from js to php - failed to open stream: http request failed

I am trying to send some json data from js to php, and pass it to mongo by REST.
The following outputs json string (that works fine later if I just put it as string in PHP file, please see snippet below).
JS to send json:
var s = JSON.stringify(send); //s contains previous data in arrays, etc
ic(s);
function ic(s){
var ajaxUrl = './iM.php';
$.getJSON(ajaxUrl,
{da: s},
function(data) {
console.log (data);
});
}
in iM.php:
$s = $_GET["da"]; // <-- doesn't work
//$s = '{"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]}'; //<-- works fine
$opts = array(
"http" => array(
"method" => "POST",
"header" => "Content-type: application/json",
"content" => $s,
),
);
$context = stream_context_create($opts);
$result = file_get_contents("https://api.mongolab.com/api/1/databases/$db/collections/$collection?apiKey=$key", false, $context);
var_dump($result); // Dumps the response document
At the firefox debugger, I can see the file is actually being called, however No data is added.
error_log file is created:
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
I also tried urlencode($s) in php, still not working.
$db, $collection and $key are defiend in php, no problem there.
What am I missing?
Basically JSON.stringify(send) function is designed in such way that it will make your json into what you are getting.
JSON.stringify(value[, replacer[, space]])
You should use this function properly. read the docs to know more.
Its basically useful if you have input value as JS array or JS object
which can be converted to single string.
You are getting '{/"r/":/"pax/",/"c/":1 in only case if you are trying to stringify a json which already in string format.
these:
var s = ['1','2','3'];
and
var s = "['1','2','3']";
are totally different things.
If you are sending an array or json object you can even send it directly
using the code above.
for example :
send = {"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]};
ic(send);
function ic(s){
var ajaxUrl = 'im.php';
$.getJSON(ajaxUrl,
{da: s},
function(data) {
console.log (data);
});
}
make sure to handle array at php side properly.
Like if you want return json, do:
$s = $_GET["da"]; //this will be array.
var jsonObject = json_encode($s);
or you can stringify it there and then provide.
or else just send string and then use json_decode to make it json in php

Error: Uncaught SyntaxError: Unexpected token &

I get an error when sending JSON data to JavaScript from the models. It looks like encoding is causing the error, but all the examples I have found work for other people. How can I properly send model data from my view to JavaScript?
view code:
def home(request):
import json
info_obj = Info.objects.all()
json_data = serializers.serialize("json", info_obj)
return render_to_response("pique/home.html", {'json_data':json_data}, context_instance=RequestContext(request))
JavaScript code:
var data = jQuery.parseJSON('{{json_data}}');
console.log(data);
The error Uncaught SyntaxError: Unexpected token &:
var data = jQuery.parseJSON('[{"pk": 1, "model": "pique.eat" ...
You must use " instead of " in the string.
The string was automatically escaped by render_to_response.
To avoid this you must mark json_data safe. Use mark_safe for it.
from django.utils.safestring import mark_safe
return render_to_response(
"pique/home.html",
{
'json_data':mark_safe(json_data)
},
context_instance=RequestContext(request))
Your data is html encoded. It should come from the server with quotes and all. Is render_to_response doing some sort of encoding? What does json_data look like before that function?

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