I am trying to access a json from the request like :
var files = req.files.fileData[0]; // This contains multiple file data
// initially it is like [object object]
for(var i=0; i<files.length; i++){
var fileDataArr = JSON.stringify(files[i]);
console.log("**********fileDataArr : "+fileDataArr);
var attachmentId = fileDataArr.name.attachmentId;
console.log("id : "+attachmentId);
}
The JSON structure is what i am getting while console fileDataArr is :
{"domain":null,"_events":{},"_eventsCount":0,"size":5056,"path":"C:\\Users\\k7000649\\AppData\\Local\\Temp\\8eb4f7b82b5646cef78f9989bb3353b1","name":"{\"fileName\":\"wiproNewIcon.png\",\"fileType\":\"image/png\",\"attachmentId\":\"99c148f3f5c1\",\"restrictedFileSize\":\"25690112 \"}","type":"image/png","hash":false,"lastModifiedDate":"2017-08-22T11:25:03.380Z","_writeStream":{"_writableState":{"objectMode":false,"highWaterMark":16384,"needDrain":false,"ending":true,"ended":true,"finished":true,"decodeStrings":true,"defaultEncoding":"utf8","length":0,"writing":false,"corked":0,"sync":false,"bufferProcessing":false,"writecb":null,"writelen":0,"bufferedRequest":null,"lastBufferedRequest":null,"pendingcb":0,"prefinished":true,"errorEmitted":false,"bufferedRequestCount":0,"corkedRequestsFree":{"next":null,"entry":null}},"writable":false,"domain":null,"_events":{},"_eventsCount":0,"path":"C:\\Users\\k7000649\\AppData\\Local\\Temp\\8eb4f7b82b5646cef78f9989bb3353b1","fd":null,"flags":"w","mode":438,"autoClose":true,"bytesWritten":5056,"closed":true},"length":5056,"filename":"{\"fileName\":\"wiproNewIcon.png\",\"fileType\":\"image/png\",\"attachmentId\":\"99c148f3f5c1\",\"restrictedFileSize\":\"25690112 \"}","mime":"image/png"}
The structure is valid but the backslash
I tried to parse the JSON to remove the backslash but it throws an error like SyntaxError: Unexpected token o, and when I am trying to access any data (fileDataArr.name.attachmentId) from the JSON it throws an error like :
TypeError: Cannot read property 'attachmentId' of undefined
at exports.xhr_upload_multi_attachment (D:\Harmony_Trunk\Development\Asset-Editor\build\harmony_development\routes\xhr_upload_attachment.js:122:39)
and I tried to replace the backslash using regex (/\g/,''), it's fine but I have file path in the JSON, hence file path is missing.
please advise me to resolve this issue.
Looks like it's already parsed but it contains nested JSON data at the name property.
Notice that the double quotes are escaped only in that property. This is because you stringified the object, which makes that property encoded a twice.
"name":"{\"fileName\":\"wiproNewIcon.png\",\"fileType\":\"image/png\",\"attachmentId\":\"99c148f3f5c1\",\"restrictedFileSize\":\"25690112 \"}"
So don't stringify at all, but parse that name property in the loop:
var parsedName = JSON.parse(files[i].name);
console.log(parsedName.attachmentId);
If that works, then try to figure out why that one property is holding its data with an encoding different from the rest. Whatever is generating your data seems to be encoding that one property separat from the rest..
Related
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.
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)
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.
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.
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.