Extra Square brackets Get added when retrieve Json data - javascript

I am Trying to retrieve data from json in my code. Json data doesn't contain any brackets. It is just any array separated by commas(,). My Problem is that when I get data using $scope, an extra sqaure bracket get added outside my output. Demo of my code is
controller.js
$http.get("serverUrl")
.success(function(data) {
$scope.sour = data;
})
.error(function(err) {
console.log("Error in source: "+JSON.stringify(err));
});
html
<div>
{{sour}}
</div
expected json
data
error
[data]
I have tried old stack solutions but none of them worked out for me.
Please share if anyone know why this error being produced, As I have used this method a hundred times before but never faced this problem.Regards.

After trying found out a solution.
.toString().replace();
solved out my problem.

As per how JSON.stringify should work as specified here, the result that you explained is as expected.
Let separator be the result of concatenating the comma character,
the line feed character, and indent.
Let properties be a String
formed by concatenating all the element Strings of partial with each
adjacent pair of Strings separated with separator. The separator
String is not inserted either before the first String or after the
last String.
Let final be the result of concatenating "[", the line
feed character, indent, properties, the line feed character,
stepback, and "]"
Which will result in a valid JSON String. The format you are requesting is confusing and is probably an invalid JSON. You can try checking the JSON using some JSON validator online. (Notice that [1,2,3,4] is valid where as 1,2,3,4 is invalid)
You are probably having a service that is expecting a malformed JSON, it will be better to fix that part instead of duck taping your JSON.
Meanwhile, the only thing you are explaining is the format you are getting and the format that is working. You haven't still specified where exactly the error happens? Is it error from HTTP request? Is it error thrown in Javascript? What is causing the error? What error messages are you getting?

Related

How can I resolve JSON parsing error 'JSON.parse: bad control character in string literal'?

In NodeJS Backend, I send my data to client as:-
res.end(filex.replace("<userdata>", JSON.stringify({name:user.name, uid:user._id, profile:user.profile}) ))
//No error here and Object is stringified perfectly
//user is object returned in mongoDB's result
The JSON string looks like this:
{"name":"Rishavolva","uid":"5f3ce234fd83024334050872","profile":{"pic":{"small_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ4fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0OH1dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.9NkGnEumn4JW8IN0KFgxgN_6_4wN8qOgezNTyzz9osY","big_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ3fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0N31dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.yxQ1GrhLsWPn8Qwu42EfTDXqaYwFtrM6f_7cAH2eLRY"},"aboutme":"I am Rishav Bhowmik\r\nand this is navratna pulaow"}}
and that UID is just a mongodb's primary key as string, and other two base 64 strings are just JWT tokens.
Now, when this JSON string reaches the Browser, I parse it with simple:
JSON.parse(`<userdata>`)
//remember I used filex.replace("<userdata>", JSON.stringify...) in the server
For reference, my MongoDB Document here is:
Now when JSON.parse is executed on the JSON string it will look like this on final JS code.
JSON.parse(`{"name":"Rishavolva","uid":"5f3ce234fd83024334050872","profile":{"pic":{"small_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ4fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0OH1dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.9NkGnEumn4JW8IN0KFgxgN_6_4wN8qOgezNTyzz9osY","big_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ3fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0N31dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.yxQ1GrhLsWPn8Qwu42EfTDXqaYwFtrM6f_7cAH2eLRY"},"aboutme":"I am Rishav Bhowmik\r\nand this is navratna pulaow"}}`)
I get this error:
Uncaught SyntaxError: JSON.parse: bad control character in string literal at line 1 column 702 of the JSON data
the string at position 702 of the JSON string is \n
First of all, how can \n be a control character?
What should I do to resolve this?
Has this problem arrised due to MONGODB result?
\n is a control character signifying a new line. In JSON, those control characters (more specifically the \) must be escaped inside strings.
This will raise the error:
JSON.parse(`{"hello":"world\n"}`)
This wont:
JSON.parse(`{"hello":"world\\n"}`)
So one way would be to use something like replace to ensure your aboutme is properly escaped before JSON serialization. See: How to escape a JSON string containing newline characters using JavaScript?
Ok have done some experimentation and have a solution.
The Trick is to do JSON.stringify() twice,
Like,
html_text.replace('/*<whatever>*/', JSON.stringify( JSON.stringify(the_object) ) )
If suppose html_text has a line which is
<script>
const object_inbrowser = JSON.parse(/*<whatever>*/)
// no need to add qotes, `JSON.stringify` in the server will do that for you
</script>

Javascript JSON.parse Invalid Character Error

I have a JSON data as below which getting from remote URL.
{"myitems":[{\"NAME\":\"JOHN\"},{\"NAME\":\"MICHAEL\"},{\"NAME\":\"CATTY\"},{\"NAME\":\"DAVID\"}]}
in JavaScript I want to parse
JSON.parse(mydata);
But I'm getting the error as:
Invalid Character
What can I do?
You need to fix the errors in the JSON. This fix should be done at source (i.e. you should change the report URL that is outputting invalid JSON so it outputs valid JSON instead).
Your string literals need to start and end with " (not \"). With the exception of "myitems", all of them have that error.
You have to remove slashes this will fix your issue:
Ex:
var str='{"myitems":[{\"NAME\":\"JOHN\"},{\"NAME\":\"MICHAEL\"},{\"NAME\":\"CATTY\"},{\"NAME\":\"DAVID\"}]}';
var output=JSON.parse(str.replace(/\\/g, ""));
above example will gives you output.

Uncaught SyntaxError: Unexpected token p in JSON at position 15

I have the Json data , which I am trying to parse in the following fiddle
but its throwing error
Uncaught SyntaxError: Unexpected token p in JSON at position 15
I am unable to paste the json here due to the large size kindly follow the fiddle
var varArray = JSON.parse(jsonData);
console.log(varArray);
Fiddle
https://jsfiddle.net/ffeLtaa6/
any suggestion ?
You have incorrectly wrapped parts of your JSON in quotes
[{"pricing":"{\"price\": ....
^
This shouldn't be here
...
.... \"standingCharge\": \"y\"}}"}]
^
This shouldn't be here
Alternatively, maybe you ARE supposed to have that part wrapped, but then you need to properly escape all backslashes within that part, i.e. \\ instead of just \.
In that case, when you do JSON.parse(jsonData) you would get objects (inside the array) that all have a single property, pricing, with a value that is itself a JSON string.
It looks like your JSON data has objects enclosed in quotations.
Take the error at position 15; The string up to that point as interpreted by parse() is:
[{"pricing":"{"
At this point your parse function is looking for a comma to continue with or end bracket to finish this object.
Now, if you skip down the string to position 3312, you'll see the character sequence }}"}. Those last two brackets match up the ones in the very beginning.
The format of your string should be [{"pricing":"{ ... }"}] if you want a string under "pricing", or [{"pricing":{" ... "}}] if you want the object representing that string.
Take a look at how the object you are JSON-ifying is being constructed, I get the feeling you may be doubling down somewhere on a stringify() function for the parent object members.
I had a the same error "Uncaught SyntaxError: Unexpected token P in JSON at position 0"
the code was working but this message was shown on console with status 200
in my case i managed to avoid the error message by changing the return type from String to Integer
like this:
//before
public String method(){
//code here
return "evrything went as expected";
}
//after
public Integer method(){
//code here
return 0;
}
I think this has something to do with the browser that is expecting to get integers, im gonna update this answer if i discover something else

NodeJS escaping back slash

I am facing some issues with escaping of back slash, below is the code snippet I have tried. Issues is how to assign a variable with escaped slash to another variable.
var s = 'domain\\username';
var options = {
user : ''
};
options.user = s;
console.log(s); // Output : domain\username - CORRECT
console.log(options); // Output : { user: 'domain\\username' } - WRONG
Why when I am printing options object both slashes are coming?
I had feeling that I am doing something really/badly wrong here, which may be basics.
Update:
When I am using this object options the value is passing as it is (with double slashes), and I am using this with my SOAP services, and getting 401 error due to invalid user property value.
But when I tried the same with PHP code using same user value its giving proper response, in PHP also we are escaping the value with two slashes.
When you console.log() an object, it is first converted to string using util.inspect(). util.inspect() formats string property values as literals (much like if you were to JSON.stringify(s)) to more easily/accurately display strings (that may contain control characters such as \n). In doing so, it has to escape certain characters in strings so that they are valid Javascript strings, which is why you see the backslash escaped as it is in your code.
The output is correct.
When you set the variable, the escaped backslash is interpreted into a single codepoint.
However, options is an object which, when logged, appears as a JSON blob. The backslash is re-escaped at this point, as this is the only way the backslash can appear validly as a string value within the JSON output.
If you re-read the JSON output from console.log(options) into javascript (using JSON.parse() or similar) and then output the user key, only one backslash will show.
(Following question edit:)
It is possible that for your data to be accepted by the SOAP consuming service, the data needs to be explicitly escaped in-band. In this case, you will need to double-escape it when assigning the value:
var s = 'domain\\\\user'
To definitively determine whether you need to do this or not, I'd suggest you put a proxy between your working PHP app and the SOAP app, and inspect the traffic.

JSON.parse string with unexpected token

Parsing this string I get an unexpected token error, what is the unexpected token?
JSON.parse("​[{"attr1":079455,"Attr2": 3},{"Attr1":847987​​,"Attr2": 3}]​​​");
I keep looking here at the documentation but I'm just not seeing what's wrong with this string? I've tried all sorts of stringifying and replacing double quotes with single ect.
JSON format does not allow leading zeroes on numbers, except for the special case of 0 or floating point numbers that begin with 0.. See the diagram that shows the format of numbers at http://www.json.org/.
So the number 079455 is not valid JSON.
You should fix the program that's generating the JSON in the first place. It should use a library function to produce JSON, instead of formatting it by hand.
If you can't, you could use the following clumsy Javascript to remove the extraneous zeroes:
json_str = json_str.replace(/":0+/, '":');
As well as incorrect number formats, you are not correctly wrapping your String. If you want to include " characters inside your string, you should wrap it with ':
JSON.parse('[{"attr1":79455,"Attr2": 3},{"Attr1":847987,"Attr2": 3}]');

Categories