how can I convert string to object in javascript - 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.

Related

JSON parse double quotes

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('\\','\\\\')}')`))

unable to read the json property if it contains backslash

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

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.

Parse ill formed JSON string

I am being sent an ill formed JSON string from a third party. I tried using JSON.parse(str) to parse it into a JavaScript object but it of course failed.
The reason being is that the keys are not strings:
{min: 100}
As opposed to valid JSON string (which parses just fine):
{"min": 100}
I need to accept the ill formed string for now. I imagine forgetting to properly quote keys is a common mistake. Is there a good way to change this to a valid JSON string so that I can parse it? For now I may have to parse character by character and try and form an object, which sounds awful.
Ideas?
You could just eval, but that would be bad security practice if you don't trust the source. Better solution would be to either modify the string manually to quote the keys or use a tool someone else has written that does this for you (check out https://github.com/daepark/JSOL written by daepark).
I did this just recently, using Uglifyjs to evaluate:
var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify;
var orig_code = "var myobject = " + badJSONobject;
var ast = jsp.parse(orig_code); // parse code and get the initial AST
var final_code = pro.gen_code(ast); // regenerate code
$('head').append('<script>' + final_code + '; console.log(JSON.stringify(myobject));</script>');
This is really sloppy in a way, and has all the same problems as an eval() based solution, but if you just need to parse/reformat the data one time, then the above should get you a clean JSON copy of the JS object.
Depending on what else is in the JSON, you could simply do a string replace and replace '{' with '{"' and ':' with '":'.

Categories