"The client needs to convert the JSON into HTML" meaning - javascript

In this article Escaping the SPA rabbit hole with modern Rails
it says that
“The client needs to convert the JSON into HTML before rendering
anything”.
What exactly does that mean?
Is the JSON payload comprised of data values, for example “price : 100” with which you update a HTML control that already exists on the client i.e a Drop down list?
,or,
does the JSON payload contain snippets of UI encoded somehow in JSON, for example an encoded Drop down list, together with the data values to populate it with, which the client will render both? in that case also altering/adding new controls to the UI (consisting of HTML) of the client?

JSON is data format it will contain data that needs to be transformed into view elements in case of browser HTML is needed before end user will see anything but such JSON data can be also used in other applications that don't need HTML and are using different means to visualize that data.

Related

When exchanging data between a browser and a server, the data can only be text. Why?

I understood why we are using JSON to exchange data between browser and server in place of XML but I could not understand why we are using only string type of JSON even we have six different value datatype, I mean why we can't use integer or Boolean or any other value datatype.
Hope you guys understand what I'm trying to say, Thanks in advance.
If I understand correctly, the limitation is because of the way data needs to be encoded to be sent over HTTP and ultimately over the wire. You json object (or xml,etc) is ultimately just a payload for HTTP (which is just a payload for tcp in turn and so on).
HTTP inherently does not and should not identify data types in payload, it is just an array for HTTP. You can select how to represent this array i.e. how to encode it; It can be string (ascii, utf-8, etc) or binary but it has to be uniform for the whole payload.
HTTP does offer different encoding methods of payload which can be interpreted by the receiver by looking at the content-type header and accordingly decode the data.
Hope this helps.
why we are using only string type of JSON
Uhm, we're not. I believe you're misunderstanding something here. HTTP responses can really contain anything; every time you download a PDF or an image from a web server, the web server is sending a binary payload, which can literally be anything. So it's not even true that all HTTP bodies must be text.
To exchange data between systems, you send bytes. For these bytes to mean anything, you need an encoding scheme. Image formats have a particular way in which bytes need to be arranged, and when properly doing so, you can send pictures with them. Same for PDFs, video, audio, and anything else (including text).
If you want to send structured data, you need to express that structure somehow. How do you send a, for example, PHP array over HTTP…? (Substitute your equivalent list data structure in your language of choice.) You can't. A PHP array is a specific data structure in memory of a PHP runtime, sending that as is over HTTP has no meaning (because it deals with internal pointers and such). This array needs to be serialised first. There are many possible serialisation methods, some of them using binary data, and some using formats which are human readable to varying degrees. You could simply join all array elements with commas and .split(',') them again on the other end, but that's rather simplistic and misses many more complex cases and edge cases.
JSON and XML (and YAML and whatnot) are human readable formats which can serialise data structures like arrays (and dictionaries and numbers and booleans etc), and which happen to be text-based (purposely, to make them developer-friendly). You can use any of those data types JSON allows. Nothing prevents you from doing so, and not using them is insane. JSON and XML also happen to be two formats easily parsed with tools built into every browser. You could use any other binary format too, but then you'd have to manually parse it in Javascript.
Communication between browser and server can be done in many ways. It's just that JSON comes out of the box. You can use protobuf, xml and plethora of other data serialization techniques to communicate with the server as long as both sides understand what's the communication medium. On the browser side, you have to probably implement protobuf, xml etc serialization/deserialization on your own in javascript.
Any valid JSON is permitted for data exchange. The keys are string quoted but the values can be strings, numbers, booleans, array or other objects itself. Though before transmission, everything is converted into a string and the receiving side parses it into the correct format.

How to safely display user's server side data in a form?

I'm using mustache to escape user data before displaying it in html via javascript.
However, when I use it to display their data in form input fields (pre populating the form after retrieving their user data from the server via AJAX), it displays entities instead.
eg
Shaun's place
displays as
Shaun's place
I'd use the three bracket trick in Mustache, but doesn't that mean the data won't be escaped, therefore making the page vulnerable?
the data stored in MySQL is user profiles.
when I get it back from the server, I run the data through the following mustache code before saving it in a local object - the idea being I don't have to keep running it through multiple lots of mustache each time I wasn to display it in various places on the site. So here's an example of one of the keys, location, being process :
var t="{{x}}",o={x:serverObjectReturn.location},x=Mustache.render(t, o);
localUserDataObject.location=x;
not 100% sure what you mean by content-type - I'm using AJAX calls, and sending the data back as JSON. The AJAX function dataType is "json". Let me know if you needed something else and I'll edit
I update the form input field so they have their profile data loaded ready for editing like so:
$("#location").val(userData.location);
That's when I get:
Shaun's place
...whereas:
$("#testerDivLocation").html(userData.location);
shows
Shaun's place
Thank you.
Here is the documentation on the subject:
All variables are HTML escaped by default. If you want to return
unescaped HTML, use the triple mustache: {{{name}}}.
So you're right that it may open you up to vulnerabilities (XSS in particular). This is useful for data that you already known is safe to render in HTML, perhaps because you've escaped and/or sanitized it elsewhere.
Since input field values are a little different because they are more raw than plain HTML, you may need to do some custom escaping either on the server-side, or in javascript just prior to the render call. This means figuring out the set of all possible characters that put an input field at risk (quotes are obvious, but what about angle brackets <, >?)
An alternative is to leave the form field values blank in HTML-land and use JavaScript up set their values through the DOM. That feels much safer to me since you are no longer trying to embed the raw data into HTML code.
var t="<input type='text' name='firstname' value=''>";
var x=Mustache.render(t);
$('input', x).val(serverObjectReturn.firstname);
(Assumes jQuery is loaded for the $ call).

Transforming api json responses for NodeJS

I'm ending up having to do hacks to convert 'true' to just true and it's creating code smell.
Is there a library like https://github.com/thephpleague/fractal that allows me to transform my response into the types I need?
In cases like this it's almost always better to fix the API to return data in a usable format rather than trying to post-process the result on the client.
In your case there are several routes you could take:
Store the list as a JSON string directly in the database.
This means you don't have to do any processing on the server and can just return it 'as is'. However you lose the ability to do queries on the data directly and need to resort to things like LIKE and string operations.
Store the data relationally, and process it on the server to turn it into JSON
Here you retain the ability to do queries on your data, but you may need to do several queries to get all the data you need and then connect it on the server. (eg. you would do one SELECT on the user table to get a user, and then you would need to do another SELECT on the friends table where the userid matches your first user. You would then need to merge these results to create your JSON.) This is usually the best way to do it.
You can also turn the result into JSON directly inside the database engine using a user defined function. For example using https://github.com/mysqludf/lib_mysqludf_json#readme
This is somewhat similar to 2, but it ties your stored procs to the JSON format.

Python to JavaScript object graph (de)serialization

I'm trying to send an object graph from Python to JavaScript running in a browser, and I was wondering whether there is a pair of ready-to-use libraries for handling serialization on the Python side and deserialization on the JavaScript side. JSON does not support object references out of the box, the docs for JS-YAML say it's not production-ready in a browser environment, and I didn't find anything for XML. Any suggestions?
edit: Here's an example for what I mean by "JSON does not support object references out of the box": I have a shop database with products and orders and a many-to-many relationship between them. If I put a bunch of orders into the Python JSON serializer, the result will contain multiple serializations (copies) of each product, because the JSON serializer has no way of saying, "I've serialized this product already, so I'll just insert a reference to it". So I put the result on the wire and deserialize it on the client, and now I have multiple JavaScript objects representing the same product, which is bad.
how about jsonpickle? JS is awesome with json out of box, adding json pickling in python is the missing link:
jsonpickle

extjs datastore send to server (datastore -> json)

Getting Json from the Server and displaying it in the grid is relatively straight forward. In the application (http://pssnet.com/~devone/extjs3/loadSelection5.html) I generate a dynamic grid datastore. I need to send this to the Server for further processing.
If there is a way to convert the data store to json, I can strigyfy it and send it a param...as in jQuery.
Otherthan looping through the whole datastore to build json, there seems no methods.
Thank you.
(I can guarantee that the following applies to Ext > 2.3)
Because Ext.data.Store stores an array of Ext.data.Record objects, it has no direct access to the underlying data (Ext.data.Record encapsulates the data), so, indeed, there's no direct way to do it. But Ext.data.Record itself has a public property called "data" (an object with the field:value properties), which you can collect into an array (e.g. using the Ext.data.Store#each method) and then encode with Ext.encode() to "stringify" it.

Categories