JSON parse double quotes - javascript

I encountered a very strange error. If I run JSON.Parse('[""d""]') then I have error: "Unexpected token d in JSON at position 3"
JSON.parse('["\"d\""]')
If I run console.log(JSON.stringify(['"d"'])) then I get '[""d""]'
console.log(JSON.stringify(['"d"']))
If I run console.log(JSON.parse(JSON.stringify(['"d"']))) then I get good result [""d""]
console.log(JSON.parse(JSON.stringify(['"d"'])))
If I use eval function then I have error: "Uncaught SyntaxError: Unexpected token d in JSON at position 3"
var someJson=JSON.stringify(['"d"']);
window.eval(`JSON.parse('${someJson}')`)
How fix it?
I use some external library and there is window.eval(JSON.parse('${JSON.stringify(t)}'))). Where t - json array with strings. String can contains double quoutes. It throws exception.
I found js changed my string value when I set it.
var someJson='["\"d\""]';
console.log(someJson);
It returns '[""d""]' and when I run JSON.Parse it is incorrect JSON.
How fix it?

JSON.parse('["\"d\""]')
\ is a special character in JS strings, so to include it in your JSON you need to escape it.
const yourString = '["\"d\""]';
const validJSON = '["\\"d\\""]'
const parsedData = JSON.parse(validJSON);
document.querySelector('#yourString').value = yourString;
document.querySelector('#validJSON').value = validJSON;
<p>Your string: <output id="yourString"></output>
<p>Valid JSON: <output id="validJSON"></output>
As a rule of thumb, embedding JSON in string literals is a waste of time and effort. You can just write the JS data structure you get from parsing the JSON.

#Quentin many thanks for idea! Result answer for me:
var someJson=JSON.stringify(['"d"']);
console.log(window.eval(`JSON.parse('${someJson.replaceAll('\\','\\\\')}')`))

Related

how can I convert string to object in javascript

I am passing dictionary from python to java script,
when I print this dictionary in java script it gets printed as string,
I confirmed this by checking its type. I want to convert this string into
object so that I can access the key value pairs,
when I try to parse this string I am getting error
data object looks like this
{
'AMARAJABAT': 'https://kite.zerodha.com/chart/ext/tvc/NFO-OPT/AMARAJABAT21SEP710CE/15738370',
'ASIANPAINT': 'https://kite.zerodha.com/chart/ext/tvc/NFO-OPT/ASIANPAINT21SEP3300CE/16292866',
'ASTRAL' : 'https://kite.zerodha.com/chart/ext/tvc/NFO-OPT/ASTRAL21SEP2100CE/15201026',
'AXISBANK' : 'https://kite.zerodha.com/chart/ext/tvc/NFO-OPT/AXISBANK21SEP800CE/16441858'
}
.
eventSource.addEventListener("online", function(e) {
let data = e.data
console.log(data) // this prints dictionary
console.log(typeof(data)) // this prints string
let obj = JSON.parse(data) // error at this line
console.log(obj)
}, true)
I am getting error as following:
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
at JSON.parse (<anonymous>)
how can I solve this?
I guess that's what happens when you ask a Python question and use the javascript tag :-P
Instead of trying to write your own JSON encoder with something like the
yield f"id: 1\ndata: {stock_dic}\nevent: online\n\n
from your comment, you should use a proper JSON encoder. Of course there's one for Python as well, even in Python.
So something like
yield json.dumps(mydictionary)
As mentioned in comments, this issue can be solved by replacing ' by ''.
before yielding dictionary I converted it to string using
json.dumps()
This way single quotations were replaced by double quoatation.

How to transform a Java object into a Javascript object?

In a jsp I use var accounts = ${sessionScope.allAccounts}; to get a Java list from session and transform it into a Javascript list. Then there is an error in Firebug:
SyntaxError: illegal character ... accounts =
[com.ailonger.po.Account#5aced6b4,
com.ailonger.po.Account#4171f1ff,...
It point out that the symbol'#' which causes the problem, but I think the symbol'#' is part of the addr. of the object. I don't know where do I make mistake or how to make the transition come true.
You could use json
This link shows how to encode java variables into json
https://www.tutorialspoint.com/json/json_java_example.htm
To decode into a JavaScript object use JSON.parse.
An example:
// myJson is the encoded json string
Var myNewObj=JSON.parse(myJson)

JSON to JavaScript, SyntaxError: Unexpected token &

I know this question has been asked numerous times, but I really donĀ“t get it.
I am creating a site in MVC, and I'm creating a JSON string from my model. I then want to pass it as argument to a JavaScript function that uses it to plot a graph.
Here is were I create the JSON string. This indeed creates a valid JSON string, I checked it at JSONLint.
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var weightsAsJsonString = serializer.Serialize(Enumerable.Select(Model, weight =>
new
{
date = weight.Date,
value = weight.Value
}));
}
Further down I create a JavaScript variable from it and pass it into the JavaScript function:
var jsonStringToGraph = #weightsAsJsonString;
google.setOnLoadCallback(drawVisualization(jsonstring));
When I run this, the console prints 'SyntaxError: Unexpected token &' at the line were I declare jsonStringToGraph. I googled around and concluded that I should put ' ' around #weightsAsJsonString, so I do that.
Anyway, in my drawVisualization, I do this:
function drawVisualization(teststring) {
.......
var parsedJson = JSON.parse(teststring);
This gives me SyntaxError: Unexpected token & Index:1
I know that the code at the bottom is what is causing the exception, but I do not understand why. Do anyone understand what I am doing wrong?
Edit: This is the weightsAsJsonString
[{"date":"\/Date(1434492000000)\/","value":100.2},{"date":"\/Date(1434578400000)\/","value":99.2},{"date":"\/Date(1434664800000)\/","value":101.2},{"date":"\/Date(1434751200000)\/","value":98.2},{"date":"\/Date(1434837600000)\/","value":97.2},{"date":"\/Date(1434924000000)\/","value":96.2},{"date":"\/Date(1435010400000)\/","value":95.2},{"date":"\/Date(1435096800000)\/","value":94.2}]
It sounds like your issue is trying to inject content via Razor into JavaScript. By default # will HTML-encode your content, which doesn't work in the context of JavaScript.
#Html.Raw(weightsAsJsonString) will work better, and then your JS will have a JavaScript object, so there's no need for the JSON.parse later on.
When you do var jsonStringToGraph = #weightsAsJsonString; you are actually defining a JSON object and not a JSON string.
Hence when you do JSON.parse(teststring); you are trying to parse an object instead of a string.
Either put apostrophes around the first declaration var jsonStringToGraph = '#weightsAsJsonString'; or simply do not try to parse it again.

Correct JS parse of URL transmitted via JSON

Here's a simplified PHP side of my ajax context:
// in a for loop
$text = "/home/ubuntu/CANE-HDD-100/y.txt"
// $text_encoded = urlencode($text);
// $text_encoded = preg_replace("/(\-)/", "%2D", $text_encoded);
$text_encoded = "%2Fhome%2Fubuntu%2FCANE%2DHDD%2D100%2Fy.txt"
$structure[$i] = $text_encoded;
echo json_encode($structure);
And here is the JS side:
request.onload = function()
{
var cleanedText = JSON.parse(this.responseText);
alert(cleanedText);
};
That throws the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
If I substitute JSON.parse(this.responseText) with decodeURI(this.responseText), I get cleanedText equal to
/home/ubuntu/CANE-HDD-100/y.txt
["%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt"]
which I dislike, since an hypotetic for loop on cleanedText would treat every element of that variable (correctly) as a character, while I'd obviously like to get elements as whole URLs.
A possible, dirty workaround is to set up some regex on cleanedText to recover every URL, but I'm wondering if there would be a much cleaner way.
w3re's comment has to be correct. You must have malformed JSON. We can show this by taking the output you do get from decodeURI, running it back through encodeURI to get what must therefore be your original string from PHP, and then trying JSON.parse on it. We get an error:
JSON.parse(encodeURI('/home/ubuntu/CANE-HDD-100/y.txt ["%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt"]'))
(program):1 Uncaught SyntaxError: Unexpected token /
That error is from Chrome, but the :1 is saying 'line 1' and the / is at column 1, so I think that's the error you're seeing.
Basically, this string is not valid JSON, because of the all the stuff at the start which is not wrapped in quotes.
However, for example, this will work, if you put it all in quotes and escape the existing ones:
JSON.parse('"/home/ubuntu/CANE-HDD-100/y.txt \\"%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt\\""')
or using an array:
JSON.parse('["/home/ubuntu/CANE-HDD-100/y.txt", "%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt"]')
or an object:
JSON.parse('{"/home/ubuntu/CANE-HDD-100/y.txt": "%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt"}')
so something must be going awry in your PHP or JavaScript in and amongst your JSON encoding and decoding. To help further, I'd need to see more of your code.

How to solve "Unterminated string literal" error while using JSON.parse method?

I get JSON data from the Yandex.Direct API, but when I try to parse it there is an error:
SyntaxError: Unterminated string literal (line 231, file
"importJSON")
My code:
var jsondata = UrlFetchApp.fetch('https://api.direct.yandex.ru/v4/json/', options);
var contextText = jsondata.getContentText();
var object = JSON.parse(contextText);
I think that this problem may be caused by invisible symbols U+2028, U+2029 (http://timelessrepo.com/json-isnt-a-javascript-subset), but I can't find it in the result file.
Please share any suggestions.
UPDATE: I cannot post the resulting JSON here because it contains sensitive production data.
The error appears when using the method
http://api.yandex.ru/direct/doc/reference/GetBanners.xml - 1 request with 10 campaign_ids = [8388422,8396871,8409767,8409910,8409979,8434877,8434885,8434891,8435993,8446636];
If I use this method ten times with one campaign_id in the request, there is no such problem. It's very strange.

Categories