Decoding JSON data saved in a database column - javascript

When i parse the JSON data i have saved in my database directly in HTML i get some messed up chars and basically it looks encoded?
Here is a sample from the HTML file:
'{"web_rendition":{"#xmlns":"","content":
How do i encode this mess or load it into a JSON object?
View class:
content = Cond.objects.get(pk=pk).con_con.con_chron
context['new_content'] = content
return context
My template:
<script>
content = "{{new_content}}";
</script>

If this is happening in the template layer, you may need a 'safe' filter to keep it from getting encoded like this.
content = "{% my_json_variable|safe %}"
safe filter in django docs

Related

How to render the quill js content using go buffalo framework

The options that i am aware of are,
Get the content of the quilljs from getContents api which gives the JSON structure. I can post this to server and store it in server.
Get the innerHTML of the div which is passed to Quill editor and store it.
Approach 1:
While displaying it back I need to write the content in my buffalo template in a variable like
<script> var contentJSON = "<%= content %>"</script>
Then once the page loaded I need to set the contents like quillInstance.setContents(contentJSON)
Approach 2:
Incase the request is compromised then the html may contain scripts unescaped. So if I try like this
c.Set("getContent", func(content string) template.HTML {
return template.HTML(html.EscapeString(content))
})
This escapes all the html entities. So all the div, styles introduced by quill js also gone with this. So the whole content looks just like a plain string.
Whats the right approach in storing the content? I am looking for a way to get this rendered in the server.
Finally i end with the following,
Helpers: render.Helpers{
"quil_for": func(content string) template.HTML {
content = strings.ReplaceAll(content, "<script>", "<script>")
content = strings.ReplaceAll(content, "<a>", "<a>")
content = strings.ReplaceAll(content, "</a>", "</a>")
content = strings.ReplaceAll(content, "</script>", "</script>")
return template.HTML(content)
},
},
instead of this
c.Set("getContent", func(content string) template.HTML {
return template.HTML(html.EscapeString(content))
})
This escapes only the script and the anchor tag and the res of html as it is.

Unable to output actual json data inside javascript script tag

Am trying to output actual json data inside javascript tag dynamically using ajax and php but this is not working anymore meanwhile json data is getting as desired. Actully when I test returned result json data from php script using console.log(response), It prints correct data in firebug console. I also have used JSON.parse(response) and also tried JSON.stringify(response) but nothing is working and not outputting (printing) in javascript script tag if we assign the data usingstackevents: response and when I see the page source code it displays only stackevents: response but not actual output like this below one
stackevents:[{"date":"2013-08-24","type":"arrowDown","graph":"g1","backgroundColor":"#85CDE6","value":"417","description":"This is description of an event"},{"date":"2013-08-25","type":"pin","graph":"g1","backgroundColor":"#85CDE6","value":"417","description":"This is description of an event"},{"date":"2013-08-26","type":"sign","graph":"g1","backgroundColor":"#85CDE6","value":"531","description":"This is description of an event"},{"date":"2013-08-27","type":"arrowUp","graph":"g1","backgroundColor":"#00CC00","value":"333","description":"This is description of an event"},{"date":"2013-08-28","type":"pin","graph":"g1","backgroundColor":"#FFFFFF","value":"552","description":"This is description of an event"},{"date":"2013-08-29","type":"arrowUp","graph":"g1","backgroundColor":"#85CDE6","value":"492","description":"This is description of an event"},{"date":"2013-08-30","type":"pin","graph":"g1","backgroundColor":"#FFFFFF","value":"379","description":"This is description of an event"},{"date":"2013-08-31","type":"pin","graph":"g1","backgroundColor":"#85CDE6","value":"767","description":"This is description of an event"},{"date":"2013-09-01","type":"flag","graph":"g1","backgroundColor":"#85CDE6","value":"169","description":"This is description of an event"},{"date":"2013-09-02","type":"arrowUp","graph":"g1","backgroundColor":"#85CDE6","value":"314","description":"This is description of an event"},{"date":"2013-09-03","type":"arrowDown","graph":"g1","backgroundColor":"#85CDE6","value":"437","description":"This is description of an event"}]
For more clarification, I want like this
stackevents:[{"date":"2013-08-24","type":"arrowDown","graph":"g1","backgroundColor":"#85CDE6","value":"417","description":"This is description of an event"},{"date":"2013-08-25","type":"pin","graph":"g1","backgroundColor":"#85CDE6","value":"417","description":"This is description of an event"},{"date":"2013-08-26","type":"sign","graph":"g1","backgroundColor":"#85CDE6","value":"531","description":"This is description of an event"},{"date":"2013-08-27","type":"arrowUp","graph":"g1","backgroundColor":"#00CC00","value":"333","description":"This is description of an event"},{"date":"2013-08-28","type":"pin","graph":"g1","backgroundColor":"#FFFFFF","value":"552","description":"This is description of an event"},{"date":"2013-08-29","type":"arrowUp","graph":"g1","backgroundColor":"#85CDE6","value":"492","description":"This is description of an event"},{"date":"2013-08-30","type":"pin","graph":"g1","backgroundColor":"#FFFFFF","value":"379","description":"This is description of an event"},{"date":"2013-08-31","type":"pin","graph":"g1","backgroundColor":"#85CDE6","value":"767","description":"This is description of an event"},{"date":"2013-09-01","type":"flag","graph":"g1","backgroundColor":"#85CDE6","value":"169","description":"This is description of an event"},{"date":"2013-09-02","type":"arrowUp","graph":"g1","backgroundColor":"#85CDE6","value":"314","description":"This is description of an event"},{"date":"2013-09-03","type":"arrowDown","graph":"g1","backgroundColor":"#85CDE6","value":"437","description":"This is description of an event"}]
in place of stackevents: response using javascript, jquery, ajax and php.
Thank You.
If you have to call the .php to GET the json data and you want to write that to the script tag of the page, here is an example: https://codepen.io/mix3d/pen/qQNZWQ
I do not cover using PHP to insert the json data into the html as the page is being rendered.
Simply include <script type="application/json" id="myscript"></script> in your html somewhere, and then with the following code, you can accept JSON data from your .php file and insert it into the script tag using innerHTML. Because a script tag is just another DOM element, you can access them with JS just like a div or button.
fetch('https://path-to.your/file.php')
.then(response => response.json())
.then(json => {
console.log(json)
document.getElementById('myscript').innerHTML = JSON.stringify(json,null,2);
})
JSON.stringify()'s 2nd and 3rd parameters are to prettyprint the JSON object into your script tag. If you do not stringify the object first, you will get [object Object] as the content of your script tag, as JS will use type-coercion to get the string of the object.
If the above code using modern JS's fetch is too much, here is an example using jQuery as well:
$.getJSON( "https://path-to.your/file.php", function( json ) {
document.getElementById('myscript').innerHTML = JSON.stringify(json,null,2);
})
Furthermore, if you wanted to go so far as to CREATE the script tag to put the JSON into:
let jsonScript = document.createElement('script');
// if you don't set the type, the browser will try to execute the text as JS instead of JSON.
jsonScript.setAttribute('type', 'application/json');
jsonScript.textContent = JSON.stringify(json);
document.head.appendChild(jsonScript); // or document.body, your choice
You will have to JSON.parse the script content to get any useful data from it though!

Sending JSON and HTML page together in node.js

I am sending my HTML file to the client in node.js as shown below
app.get('/get', function(req, res) {
res.render(index.html);
});
Here, index.html refers to a json file.
How can I send both together or refer the json file in the client?
If you don't want to request the JSON file from the client as an independent HTTP request you can do one of the following:
Full server side rendering:
Use a template technology like moustache or handlebars, and try to render that data inline with the response. For example if you your JSON file returns a name and an address the index.html could look like:
<div>
<span>Name: {{name}} </span>
<address>Address: {{address}} </span>
<div>
Then when rendering you could pass a js object with properties name and address to the template and you wouldn't need to ask for the JSON file separately. This example follows moustache guidelines just in case I wasn't explicit enough.
Inline object
A bit like the previous solution but less elegant, you can add the full JSON response as an object with within a script tag, and then use it however you see fit. Try to append a block to he HEAD of index.html like this:
<script>
var myObject = <contents of your JSON object>
</script>
The other possible solution was just described in another answer.
I hope this helps.
HTTP only sends one resource at a time. If your page is requesting a JSON file, it needs to be served as a second request.
Alternatively, you can render HTML with a <script> block that has a variable assignment with your JSON-encoded data as a value.
You can't send two types of files back in a single request, but you could either do an ajax call in the html to get the json you need:
<script type="text/javascript">
var json_data;
$.getJSON("URL_HERE", function(data) { json_data = data; });
</script>
or add the json to the html as a javascript object via a template engine (jade shown below):
script(type="text/javascript").
var json_data = #{ JSON.stringify(JSON_OBJECT_HERE) }

Safely Using JSON with html inside of the JSON in Django Templates

How do you safely render JSON data in a django webapp?
On the server in django I generate JSON data and then render that JSON data in a django template. The JSON occasionally contains snippets of html. Most of the time, that's fine, however if the </script> tag is inside the JSON data when it is rendered, it destroys the surrounding javascript.
For example...
On the server, in python I'll have this:
template_data = {
'my_json' : '[{"my_snippet": "<b>Happy HTML</b>"}]'
}
# pass the template data to the django template
return render_to_response('my_template.html', template_data, context_instance = c)
And then in the template:
<script type="text/javascript">
var the_json = {{my_json|safe}};
</script>
... some html ...
The resulting html works fine and looks like this:
<script type="text/javascript">
var the_json = [{"my_snippet": "<b>Happy HTML</b>"}];
</script>
... some html ...
However, you run into problems when, on the server, the JSON looks like this:
template_data = {
'my_json' : '[{"my_snippet": "Bad HTML</script>"}]'
}
return render_to_response('my_template.html', template_data, context_instance = c)
Now, when it's rendered, you'll get:
<script type="text/javascript">
var the_json = [{"my_snippet": "Bad HTML</script>"}];
</script>
... some html ...
The closing script tag within the JSON code is treated as closing the entire script block. All of your javascript will then break.
One possible solution is to check for </script> when passing the template data to the template, but I feel like there is a better way.
Safely insert the JSON as a string, and then call JSON.parse on it
Use escapejs instead of safe. It is designed for outputting to JavaScript.
var the_json = '{{my_json|escapejs}}';
To get a JavaScript object you then need to call JSON.parse on that string. This is always preferable than dumping a JSON-encoding into your script and evaluating it directly, for security reasons.
A useful filter to get python objects directly to the client that I use is this:
#register.filter
def to_js(value):
"""
To use a python variable in JS, we call json.dumps to serialize as JSON server-side and reconstruct using
JSON.parse. The serialized string must be escaped appropriately before dumping into the client-side code.
"""
# separators is passed to remove whitespace in output
return mark_safe('JSON.parse("%s")' % escapejs(json.dumps(value, separators=(',', ':'))))
And use it like:
var Settings = {{ js_settings|to_js }};

How can one incorporate JSON data with the returned HTML on the first request to the home page?

My scenario is this - the user asks for the home page and then the javascript code of the page executes an ajax GET request to the same server to get some object.
The server keeps the home page as a jade template.
So, right now it takes two roundtrips to load the home page:
GET the home page
GET the JSON object
I am OK with it, but just out of curiosity - what are my options to incorporate the object requested later into the initial GET request of the home page?
I see one way is to have a hidden html element, which inner HTML would be the string representation of the object. A bit awkward, but pretty simple on the server side, given that the home page jade template is preprocessed anyway.
What are my other options?
Please, note that I am perfectly aware that sparing this one roundtrip does not really matter. I am just curious about the techniques.
Another option is to always return a JSON object, then the HTML for your home page would be the value of some property on this object. This would probably require some changes on your client-side logic, though.
One more option: instead of a hidden HTML input/textarea containing a JSON string, the home page code could contain a script block where an object literal is declared as a variable. Something like this:
<script>
var myObj = ... // Your JSON string here.
// myObj will be an object literal, and you won't need
// to parse the JSON.
</script>
The initial GET request will retrieve just that document. You can have additional documents loaded defined as scripts at the bottom of your page, so you don't need to do a XHR, for the initial load.
For instance:
GET /index.html
//At the bottom you have a <script src="/somedata.js"></script>
GET /somedata.js
//here you define you var myObj = {}.... as suggested by bfavertto
Depending on which server side technology are you using, this could be for instance in MVC3
public partial class SomeDataController : BaseController
{
public virtual ContentResult SomeData()
{
var someObject = //GET the JSON
return Content("var myObj = " + someObject, "application/javascript");
}
}
You can embed the Json data inside a hidden tag in your HTML. At runtime, your javascript reads the data from this hidden tag instead of making a Json call (or make the call if this data is not available).
<!--the contents of this div will be filled at server side with a Json string-->
<div id="my-json-data" style="display:hidden">[...json data...]</div>
on document ready:
var jsonStr = document.getElementById( "my-json-data" ).innerHTML;

Categories

Resources