How to transform a Java object into a Javascript object? - javascript

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)

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.

JS parse object wrapped in a string using same quotes as object keys

Consider the following event payload data returned via WS:
{
id: "1",
foo: "{"bar":"baz"}"
}
The current output of JSON.stringify(event.foo):
"{\"bar\":\"baz\"}"
Also consider the backend have no real way to return the foo value formatted differently and I need to find a way to parse the string associated to this foo key in order to access it's value of bar.
The identified problem is the fact that the quotes used to wrap the whole supposed object are the sames used in the object itself, resulting in making JSON.parse() impossible.
I'm wondering if there is a "clean" way to achieve this.
So far, I tried:
using JSON.parse() which fails due to the format of the string raising Unexpected end of JSON input
trimming external quotes and converting inner ones to single then parsing, results in same error.
using new Object(...) based on the string (trimmed of external quotes)
replacing all quotes with single ones and wrapping it again in double ones to parse it.
Any input appreciated
The problem here is the backend should really be fixed, but some reason you can not do it. Next issue is you can "fix it" on the front end, but you are putting a band aid on the problem and it will fall off when the data that comes back is not what you expect. So the solutions will be error prone unless you know the data coming back will be a specific type.
With this said, you can fix the invalid JSON that you have in your simple example with a couple of regular expressions. Problem is, if your data contains characters such as } in the text, this is going to fail.
var response = `
{
id: "1",
foo: "{"bar":"baz"}",
goo: "{"gar":"gaz"}"
}
`
var reObj = /"(\{[^}]*})"/
while (response.match(reObj)) {
response = response.replace(reObj, '$1')
}
var reKey = /^\s+(\S+):/m
while (response.match(reKey)) {
response = response.replace(reKey,'"$1":')
}
var obj = JSON.parse(response)
console.log(obj)

Parsing encoded php object having a property containing html markup

I need to json encode a php object called 'contact' in my controller, pass it to my view and then parse it using javascript. One of the object properties contains HTML markup, which seems to cause a lot of issues. I have been running in to a lot of trouble successfully parsing the object.
I keep getting the following javascript error when calling JSON.parse().
VM4464:1 Uncaught SyntaxError: Unexpected token & in JSON at position 1
at JSON.parse (<anonymous>)
What I tried:
PHP
$contact = htmlspecialchars(json_encode($contact), ENT_QUOTES, 'UTF-8');
Front end
var contact = JSON.parse("{{ $contact }}");
just yesterday I had the same problems, apparently it has something to do with blade escaping special character. I found the answers on this site,
try
var contact = JSON.parse('{!! json_encode($contact) !!}');
notice the use of {!! instead of {{, and try to experiment the usage of single/double quotes, or even without quotes, maybe?

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.

JSON from Newtonsoft to JavaScript

So, I have a some json data which I create in my controller like so:
Notes = JsonConvert.SerializeObject(contact.Notes.OrderBy(x => x.DateLogged).Select(x => new
{
id = x.Id,
date = x.DateLogged,
content = x.Content,
logged = x.Username
}))
This then gets passed to the view, now which statment can I do to achieve the results of having a variable contain that json data:
var data = '#Html.Raw(Model.Notes)'
or
var data = JSON.parse('#Html.Raw(Model.Notes)');
EDIT
the content variable holds some "\n" which when passed to the view using the first choice from above generates an error, saying
Unexpected Token
it only does it with \n so what is going wrong here? the bottom method doesn't quite work.
var data = JSON.parse('#Html.Raw(Model.Notes)');
This doesn't work - you can't put a JSON literal inside a JavaScript string. Any backslash in it will be an escape character to the JavaScript parser, not the JSON parser. A newline comes out like:
var data = JSON.parse('{"content": "abc\ndef"}');
which means the string you are asking JSON to parse is:
{"content": "abc
def"}
which is not valid as you can't have a literal newline in a JSON string.
To do this with JSON.parse you would have to JS-string-literal encode the JSON output, so you would end up with "abc\\ndef". The alternative would be to include the JSON directly in the script block as var data = #Html.Raw(Model.Notes);, but there are problems with this to do with the differences between JS and JSON (primarily characters U+2028 and U+2029) and the enclosing HTML context (ie what the sequence </script does).
Getting the escaping right here is harder than it looks, so you should avoid injecting anything into a <script> block. Better to put in-page JSON data in a data- attribute and read it from the DOM; this way you can use the normal HTML escaping Razor gives you by default.
<div id="notes" data-notes="#Model.Notes">
...
var data = JSON.parse(document.getElementById('notes').getAttribute('data-notes'));
bobince is obviously correct in what he says, it makes so much sense, thanks for that.
However, my solution was to simply do:
var data = #Html.Raw(Model.Notes);
Because, Newtonsoft already has converted it to a proper JSON format, so all it needs to do, is be assigned to a variable to be manipulated.
I think grabbing the content from a the HTML DOM is a bit too much for this.

Categories