How can I access JSON.#attribute from an XML Converted on Javascript - javascript

I got a JSON converted from XML.
So, how can I get json.#attribute.something.
# <-- this one will make javascript error
I use Javascript.

Making a great exercise of imagination, I suppose you've used jQuery to download some JSON through AJAX and you have an object with a key called "#attribute", such as this:
var foo = {
"#attribute": 33
}
You just need to use square brackets:
console.log(foo["#attribute"])

Related

Passing a Django Object to Javascript

Below is the simplified version of my code
view.py:
context['colorObj'] = Colors.objects.all()
Now on template, I can just loop through {{colorObj}} to get the individual values inside the object.
However on JavaScript, this is not the case.
If I want to assign to a variable my colorObj, it just does not work(or maybe I am wrong).
Here is I first thought I should do:
JavaScript:
var colorObj = {{colorObj}};
the value of colorObj is still empty, and there are warning marks on the {{}}. Others suggested to use "" on the Javascript like var colorObj = "{{colorObj}}"; but JavaScript just treat this as a simple String.
Other suggestion is this:
from json import dumps
...
colorObj = Colors.objects.all()
context['colorObj'] = dumps(colorObj)
Then on JS:
var colorObj = {{colorObj| safe}};
But I got an error Object of type QuerySet is not JSON serializable pointing the error to the dumps line.
Note, I am using Django3.1.5
Though I asked about how to get the data from db to Javascript with this method, I proceeded to a different method since it matches my use case. I used #Mahdi Firouzjah's answer for this.
you could use ajax in templates and __ serialize in backend side.
then using javascript you're able to work with that object.

JSON Parsing error with backslash

I have been trying to figure out why the following JSON input will be failed to parse in JSON.parse function.
{"World":"Hello\\Test"}
The json above is being returned by JSON.NET.
I have tried multiple methods to get this working. As you can see the backslash is escaped and https://jsonlint.com/ is able to parse it.
I have a failing sample at https://jsfiddle.net/ckp0uc0p/3/ as well.
Any help will be appreciated.
The best way to inject JSON into JavaScript source code (when generating the JavaScript with a server side language), is to inject it directly where you need it, not inside a string literal that needs to be parsed.
For example:
var foo = <json blob>;
so that the result will be
var foo = {"World":"Hello\\Test"};
JavaScript will interpret this as an object literal resulting in an object, which is what you want to get anyway. This avoids all the problems with "nested" escape sequences.
You need to add two \\ for every backslash you want to have it displayed. If you're parsing a json, to display 2 backslashes you need to add 4.
// inside a string to be parsed as json
var json = '{"World":"Hello\\\\Test"}'
console.log(JSON.parse(json))
// directly in an object
var object = {"World": "Hello\\Test"}
console.log(object)
try
{
var res = '{"World":"Hello\\\\Test"}';
var s = JSON.parse(res);
console.log(JSON.stringify(s));
} catch(error) {
alert(error);
}

UTF-8 symbol is converted when inserted to dom

I have a following problem, i am building app that uses data stream from ajax calls, the data that is coming is therefore escaped inside json string.
example: 1°Set
When i insert that data to DOM it is being converted like this: 1°Set
I dont use any libraries like jQuery, pure Javascript.
I tried to store converted name also in another place but i cannot seem to convert it manually, i tried following functions:
var test = function(str) {
console.log(unescape(encodeURIComponent(str)) );
console.log(decodeURIComponent(escape(str)) );
};
test('1°Set');
It stays the same, does anyone have an idea how to convert it to a DOM like version?
I have a following problem, i am building app that uses data stream from ajax calls, the data that is coming is therefore escaped inside json string.
example: 1°Set
Sounds like you're having a problem because your backend serves a JSON that looks like:
{
"something": "1°Set"
}
Instead of a string "1°Set", you're serving HTML source code that amounts to "1°Set". This looks very unnecessary. I cannot see a good reason of using HTML escaping inside JSON, unless you actually want your JSON to actually contain a part of HTML source (with formatting and everything), rather than just a string.
My suggestion: Let's keep it simple and instead serve something like:
{
"something": "1°Set"
}
or equivalently escape it properly using JSON syntax:
{
"something": "1\u00b0Set"
}
Now you'll JavaScript will receive a plain string that can be easily displayed, for example inside element.textContent or element.value or anywhere else. You won't even need any conversions.

Can't pass double quotes JSON to Javascript from Android Java

Scenario:
TLDR; Why can I not pass ("") from Android to JavaScript, only ('') works?
I'm sending a JSON object from Android to JavaScript through:
mWebView.loadUrl("javascript:foo(\"" + bar + "\")");
To my knowledge this calls the javascript function foo() passing it the value of bar.
The bar variable is a JSON object for example:
bar = "{'id':'"+barID+"','title':'"+barTitle+"'}";
Now on the javascript side the function foo() does the following:
function foo(json){
var completeJsonObject;
json = json.replace(/'/g, '"');
completeJsonObject = JSON.parse(json);
}
This works perfectly as it replaces the (') with ("") and then the json can be parsed.
However to avoid having to replace I could just format the json on the java side with ("") instead like bellow right?
bar = "{\"id\":\""+barID+"\",\"title\":\""+barTitle+"\"}";
Well no, as soon as I do that the JavaScript gives me an unexpected token error.
Is there a better way to fix this than with my solution?

How to parse JSON in JavaScript to take value

I am really stuck in parsing a JSON string and take it's values. I got the JSON string as
{"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"fred#websecurify.com", "usergroup_id":"1","status":"1","ip_enable":"N","priv":"0","expire":""},"data":{ "1":{"5":{"last_update":"2010-12-13 16:16:16","status":"0"},"3":{"last_update":"2010-12-13 16:41:48","status":"1"}},"2":{"6":{"last_update":"2010-12-13 16:41:48","status":"1"}}},"server_array":[{"id":"1","name":"anes.yyy.net"},{ "id":"2","name":"neseema.xxx.net"}],"service_array":[{"id":"5","name":"POP3"}, {"id":"6","name":"Cpanel"},{"id":"3","name":"SMTP"}],"sort_by":"servername", "sort_order":"ASC","pagelinks":"","totrows":"2","offset":"0","limitvalue":"10", "rows_monitor":2,"current":"monitor","uri":false}
How to Parse this and take the Results for further
processing in JavaScript
You should use jQuery.parseJSON. It will use native JSON if available, and only use eval if necessary, after a sanity check.
Use JSON.parse (redirected from http://json.org), alternatively MDN
Json is already some javascript. so parsing is just using eval
like:
var foobar = eval(yourjson);
alert(foobar.user);
Also jquery has some function for it jquery.parseJSON
like:
var foobar = $.parseJSON(yourjson);
Jquery is better because it would make some checks and perform better.
First, download jQuery.
Second, include it in your page.
Third, if your variable is this:
var jsonString = '{"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"fred#websecurify.com", "usergroup_id":"1","status":"1","ip_enable":"N","priv":"0","expire":""},"data":{ "1":{"5":{"last_update":"2010-12-13 16:16:16","status":"0"},"3":{"last_update":"2010-12-13 16:41:48","status":"1"}},"2":{"6":{"last_update":"2010-12-13 16:41:48","status":"1"}}},"server_array":[{"id":"1","name":"anes.yyy.net"},{ "id":"2","name":"neseema.xxx.net"}],"service_array":[{"id":"5","name":"POP3"}, {"id":"6","name":"Cpanel"},{"id":"3","name":"SMTP"}],"sort_by":"servername", "sort_order":"ASC","pagelinks":"","totrows":"2","offset":"0","limitvalue":"10", "rows_monitor":2,"current":"monitor","uri":false}';
then,
var parsedJson = jQuery.parseJSON(jsonString);
will give you the desired parsed object that's ready for manipulation.
I tried out your JSON string on JSONLint and it says it's valid, so you should have no problems with it.
you probably got your json in som String variable
var json = '{"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"fred#websecurify.com", "usergroup_id":"1","status":"1","ip_enable":"N","priv":"0","expire":""},"data":{ "1":{"5":{"last_update":"2010-12-13 16:16:16","status":"0"},"3":{"last_update":"2010-12-13 16:41:48","status":"1"}},"2":{"6":{"last_update":"2010-12-13 16:41:48","status":"1"}}},"server_array":[{"id":"1","name":"anes.yyy.net"},{ "id":"2","name":"neseema.xxx.net"}],"service_array":[{"id":"5","name":"POP3"}, {"id":"6","name":"Cpanel"},{"id":"3","name":"SMTP"}],"sort_by":"servername", "sort_order":"ASC","pagelinks":"","totrows":"2","offset":"0","limitvalue":"10", "rows_monitor":2,"current":"monitor","uri":false}';
now you can easily parse it via jQuery (you also can parse it via native javaScript eval, but there are some security issues, badly formated input string f.e., that is covered with jQuery and not in eval)
result = jQuery.parseJSON(json);
Now you can easily acces your json object
alert('Hello user, your name is ' + json.user.firstname);
You don't need jQuery, in ECMAScript5 JSON object will be supported natively and with it you can use JSON.parse method to parse a string into a JS object. IE9 will support ES5 and FF and Chrome already do.
For the moment you can use json2.js (you can look at the source here) as fallback for the browsers that don't support JSON natively.

Categories

Resources