Use case for a JSON file - json

I've used JSON a number of times within AJAX requests to perform asynchronous writes/reads of a database. I've been trying to better understand JSON and its uses within different programming environments and one of the questions I've been curious about is: what are the common use cases for JSON as external file (rather than just as an object that is passed within AJAX requests)?
More specifically, what are some use cases in which a .json file would be better suited than simply using temporary JSON objects to pass between AJAX requests? Any insight on this would be much appreciated.

I am not that familiar with AJAX etc., but JSON is so popular that many programming languages support it - not just Java and related languages.
In itself JSON simply holds information - it's merely a format for storing data.
It can often be used to transfer data between languages. Personally, I am also using JSON to store my objects to persistent data storages and then later on rebuild the objects alongside the .class schematics. For example, Google created GSON to easily turn objects into JSON and back. Very handy!
You should also think about: How do you transfer an object from one machine to another?
To sum it up: It's simple, it doesn't create massive overhead, it's even easy to read. And most important of all: So many tools offer JSON support.
Edit:
To show the simplicity of re-building from JSON, here's an example from my game:
public static Player fromJson(String json) {
if(json != null && !json.isEmpty()) {
return gson.fromJson(json, Player.class);
}
return new Player(); //no save game present. Use default constructor
}

Related

Django - serialize complex context structure with models and data

In django view I want to be able to serialize whole context, that is usually used to send to template (typically by calling render and passing locals).
I want to experiment with SPA+API and possibilities to go forward with and I'd like to create function, that would serialize locals to json and return it as json response.
Now problem is, that locals is typically mix of lists, dists and querysets of models.
I can serialize models using django.core.serializers or using django-rest-framework. I can serialize dict with primitive types using json library, but I don't know any simple way how to do mix of those.
Ideal would be way to go through locals dictionary and replace all found models with their serialized representations and then put it all together, maybe even specify before what serializer (in sense of drf) to use for which model. But I really don't want to reinvent wheel in case it already exists.
Anoher question is - is this even a good idea to try to do this? Return json context as alternative to server side rendering? I am in prototyping stage so I am still thinking of how to move forward and any input in the area is appreciated.
I would recommand to go with DRF
ModelSerializer will return a Json encoded array of model
Serializer with DictField will return a Json encoded dict
Serializer with ListField will return a Json encoded list
You can create Serializer with field is another Serializer for nesting purpose.
https://www.django-rest-framework.org/api-guide/fields/#composite-fields
https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
For your' question is this a good idea, i would said :
If you push data to an external source (not django) it's fine
If you push data to django template it's a bad idea, you loose a lot of django power :(

angular and turning json data into real objects (and vice-versa)

To keep this simple:
I have classes defined in typescript which have methods and properties (with lots of getter/setter logic). I then retrieve json data matching such classes. I need to be able to project these json objects into my "smart" classes. I know about class transformer but I wonder if this is really go-to approach to do this kind of stuff. Furthermore, I'm planning on using ngrx, so this whole class-transformation just looks wrong (server to json, json to state, state to class? and viceversa? I just dont see a clear pattern.
Any clarity is appreciated. Thanks!
I'm doing almost exactly what you describe in a fairly large app.
I'm using class-transformer to transform the JSON from http calls to instances of the appropriate objects, and then using the resulting objects as state in a store (except that I'm using Redux instead of ngrx).
I find that it works very well.
I'm not sure exactly what you mean by "server to json, json to state, state to class? and viceversa?".
For me (using your terminology), it's server to json, json to class, class to state
(but state is just a collection of objects, i.e. class instances. I.E. state is objects).
If I need to send state back to the server, then yes, I typically pull the appropriate objects from the store, serialize them to JSON, and send them to the server. But...the Angular HttpClient does the serialization for you, so you don't typically have to write that part, unless you need some custom serialization.

Binding JSON to nested Grails Domain Objects

I'm developing a RESTful interface which is used to provide JSON data for a JavaScript application.
On the server side I use Grails 1.3.7 and use GORM Domain Objects for persistence. I implemented a custom JSON Marshaller to support marshalling the nested domain objects
Here are sample domain objects:
class SampleDomain {
static mapping = { nest2 cascade: 'all' }
String someString
SampleDomainNested nest2
}
and
class SampleDomainNested {
String someField
}
The SampleDomain resource is published under the URL /rs/sample/ so /rs/sample/1 points to the SampleDomain object with ID 1
When I render the resource using my custom json marshaller (GET on /rs/sample/1), I get the following data:
{
"someString" : "somevalue1",
"nest2" : {
"someField" : "someothervalue"
}
}
which is exactly what I want.
Now comes the problem: I try to send the same data to the resource /rs/sample/1 via PUT.
To bind the json data to the Domain Object, the controller handling the request calls def domain = SampleDomain.get(id) and domain.properties = data where data is the unmarshalled object.
The binding for the "someString" field is working just fine, but the nested object is not populated using the nested data so I get an error that the property "nest2" is null, which is not allowed.
I already tried implementing a custom PropertyEditorSupport as well as a StructuredPropertyEditor and register the editor for the class.
Strangely, the editor only gets called when I supply non-nested values. So when I send the following to the server via PUT (which doesn't make any sense ;) )
{
"someString" : "somevalue1",
"nest2" : "test"
}
at least the property editor gets called.
I looked at the code of the GrailsDataBinder. I found out that setting properties of an association seems to work by specifying the path of the association instead of providing a map, so the following works as well:
{
"someString" : "somevalue1",
"nest2.somefield" : "someothervalue"
}
but this doesn't help me since I don't want to implement a custom JavaScript to JSON object serializer.
Is it possible to use Grails data binding using nested maps? Or do I really heave to implement that by hand for each domain class?
Thanks a lot,
Martin
Since this question got upvoted several times I would like to share what I did in the end:
Since I had some more requirements to be implemented like security etc. I implemented a service layer which hides the domain objects from the controllers. I introduced a "dynamic DTO layer" which translates Domain Objects to Groovy Maps which can be serialized easily using the standard serializers and which implements the updates manually. All the semi-automatic/meta-programming/command pattern/... based solutions I tried to implement failed at some point, mostly resulting in strange GORM errors or a lot of configuration code (and a lot of frustration). The update and serialization methods for the DTOs are fairly straightforward and could be implemented very quickly. It does not introduce a lot of duplicate code as well since you have to specify how your domain objects are serialized anyway if you don't want to publish your internal domain object structure. Maybe it's not the most elegant solution but it was the only solution which really worked for me. It also allows me to implement batch updates since the update logic is not connected to the http requests any more.
However I must say that I don't think that grails is the appropriate tech stack best suited for this kind of application, since it makes your application very heavy-weight and inflexbile. My experience is that once you start doing things which are not supported by the framework by default, it starts getting messy. Furthermore, I don't like the fact that the "repository" layer in grails essentially only exists as a part of the domain objects which introduced a lot of problems and resulted in several "proxy services" emulating a repository layer. If you start building an application using a json rest interface, I would suggest to either go for a very light-weight technology like node.js or, if you want to/have to stick to a java based stack, use standard spring framework + spring mvc + spring data with a nice and clean dto layer (this is what I've migrated to and it works like a charm). You don't have to write a lot of boilerplate code and you are completely in control of what's actually happening. Furthermore you get strong typing which increases developer productivity as well as maintainability and which legitimates the additional LOCs. And of course strong typing means strong tooling!
I started writing a blog entry describing the architecture I came up with (with a sample project of course), however I don't have a lot of time right now to finish it. When it's done I'm going to link to it here for reference.
Hope this can serve as inspiration for people experiencing similar problems.
Cheers!
It requires you to provide teh class name:
{ class:"SampleDomain", someString: "abc",
nest2: { class: "SampleDomainNested", someField:"def" }
}
I know, it requires different input that the output it produces.
As I mentioned in the comment earlier, you might be better off using the gson library.
Not sure why you wrote your own json marshaller, with xstream around.
See http://x-stream.github.io/json-tutorial.html
We have been very happy with xstream for our back end (grails based) services and this way you can render marshall in xml or json, or override the default marshalling for a specific object if you like.
Jettison seems to produce a more compact less human readable JSON and you can run into some library collision stuff, but the default internal json stream renderer is decent.
If you are going to publish the service to the public, you will want to take the time to return appropriate HTTP protocol responses for errors etc... ($.02)

How to get list of objects by using jQuery.get or post

I am using jQuery.get/post methods in my Struts2 application.
See the following code. This URL return "success" and "error". It will hit a method and return a string (the struts2). I have made JSPs that contatin these strings in them.
But I want to change this approach. If I have to return a list of objects. What I will do. How a method that return a list of objects will be handeled in jQuery. How JSON will help me? I need a pointer on it.
I hope my point is understood.
jQuery.post("register_user.action" , jQuery("#user_form").serialize(),
function(data){
if (data == "success"){
jQuery("#success").dialog("open");
}else if (data == "error"){
jQuery("#error").dialog("open");
}
});
It's difficult to answer the question "How will JSON help you?" without specific context of what you are doing but I can offer up the generic answer. JSON stands for javascript object notation. It has many uses but relative to your question, it allows you to send a serialized representation of your data from the server down to your client without the "bloat" that comes with XML. Another advantage of using JSON over XML is modern browsers have built in support for it so you don't have to worry about parsing data.
You access the data like properties of a class.
Taking your example, you could return an object (I typically use anonymous objects in scenarios like this) with a single BOOL property called 'success' serialized to JSON. You could then avoid string comparisons in your javascript. In my personal opinion, the code becomes much cleaner.
jQuery.post("register_user.action" , jQuery("#user_form").serialize(),
function(data){
if (data.success){
jQuery("#success").dialog("open");
}else{
jQuery("#error").dialog("open");
}
});
This would be the most basic of examples. JSON becomes much more powerful if you return a serialized list of data from the server to the client. Let's say you send a list of comments in JSON. You could then use jquery templating to bind that list against a template and vuala, you can quickly display that day in your format of choice without manually iterating through all items.
As I mentioned, it's hard to be to specific as I don't know exactly what you are looking to accomplish but I hope this helps.

What is JSON and what is it used for?

I've looked on Wikipedia and Googled it and read the official documentation, but I still haven't got to the point where I really understand what JSON is, and why I'd use it.
I have been building applications using PHP, MySQL and JavaScript / HTML for a while, and if JSON can do something to make my life easier or my code better or my user interface better, then I'd like to know about it. Can someone give me a succinct explanation?
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.
An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight
You can find a lot more info on the official JSON web site.
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
JSON Structure
Here is an example of JSON data:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}
JSON in JavaScript
JSON (in Javascript) is a string!
People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.
In Javascript var x = {x:y} is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'. x is an object of type string not an object in its own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');, x is now an object but this is not JSON anymore.
See Javascript object Vs JSON
When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).
Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.
Example on how to use the JSON parser (with the json from the above code snippet):
//The callback function that will be executed once data is received from the server
var callback = function (result) {
var johnny = JSON.parse(result);
//Now, the variable 'johnny' is an object that contains all of the properties
//from the above code snippet (the json example)
alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};
The JSON parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:
var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}
The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)
Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.
References
JSON.org
Wikipedia
Json in 3 minutes (Thanks mson)
Using JSON with Yahoo! Web Services (Thanks gljivar)
JSON to CSV Converter
Alternative JSON to CSV Converter
JSON Lint (JSON validator)
The Concept Explained - No Code or Technical Jargon
What is JSON? – How I explained it to my wifeTM
Me: “It’s basically a way of communicating with someone in writing....but with very specific rules.
Wife: yeah....?
Me: In prosaic English, the rules are pretty loose: just like with cage fighting. Not so with JSON. There are many ways of describing something:
• Example 1: Our family has 4 people: You, me and 2 kids.
• Example 2: Our family: you, me, kid1 and kid2.
• Example 3: Family: [ you, me, kid1, kid2]
• Example 4: we got 4 people in our family: mum, dad, kid1 and kid2.
Wife: Why don’t they just use plain English instead?
Me: They would, but remember we’re dealing with computers. A computer is stupid and is not going to be able to understand sentences. So we gotta be really specific when computers are involved otherwise they get confused. Furthermore, JSON is a fairly efficient way of communicating, so most of the irrelevant stuff is cut out, which is pretty hand. If you wanted to communicate our family, to a computer, one way you could do so is like this:
{
"Family": ["Me", "Wife", "Kid1", "Kid2"]
}
……and that is basically JSON. But remember, you MUST obey the JSON grammar rules. If you break those rules, then a computer simply will not understand (i.e. parse) what you are writing.
Wife: So how do I write in Json?
A good way would be to use a json serialiser - which is a library which does the heavy lifting for you.
Summary
JSON is basically a way of communicating data to someone, with very, very specific rules. Using Key Value Pairs and Arrays. This is the concept explained, at this point it is worth reading the specific rules above.
In short - JSON is a way of serializing in such a way, that it becomes JavaScript code. When executed (with eval or otherwise), this code creates and returns a JavaScript object which contains the data you serialized. This is available because JavaScript allows the following syntax:
var MyArray = [ 1, 2, 3, 4]; // MyArray is now an array with 4 elements
var MyObject = {
'StringProperty' : 'Value',
'IntProperty' : 12,
'ArrayProperty' : [ 1, 2, 3],
'ObjectProperty' : { 'SubObjectProperty': 'SomeValue' }
}; // MyObject is now an object with property values set.
You can use this for several purposes. For one, it's a comfortable way to pass data from your server backend to your JavaScript code. Thus, this is often used in AJAX.
You can also use it as a standalone serialization mechanism, which is simpler and takes up less space than XML. Many libraries exists that allow you to serialize and deserialize objects in JSON for various programming languages.
In short, it is a scripting notation for passing data about. In some ways an alternative to XML, natively supporting basic data types, arrays and associative arrays (name-value pairs, called Objects because that is what they represent).
The syntax is that used in JavaScript and JSON itself stands for "JavaScript Object Notation". However it has become portable and is used in other languages too.
A useful link for detail is here:
http://secretgeek.net/json_3mins.asp
The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.
JSON is JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections as compared to XML.
I suggest JSON be used in any AJAX-like applications where XML would otherwise be the "recommended" option. The verbosity of XML will add to download time and increased bandwidth consumption ($$$). You can accomplish the same effect with JSON and its mark-up is almost exclusively dedicated to the data itself and not the underlying structure.
the common short answer is: if you are using AJAX to make data requests, you can easily send and return objects as JSON strings. Available extensions for Javascript support toJSON() calls on all javascript types for sending data to the server in an AJAX request. AJAX responses can return objects as JSON strings which can be converted into Javascript objects by a simple eval call, e.g. if the AJAX function someAjaxFunctionCallReturningJson returned
"{ \"FirstName\" : \"Fred\", \"LastName\" : \"Flintstone\" }"
you could write in Javascript
var obj = eval("(" + someAjaxFunctionCallReturningJson().value + ")");
alert(obj.FirstName);
alert(obj.LastName);
JSON can also be used for web service payloads et al, but it is really convenient for AJAX results.
Update (ten years later): Don't do this, use JSON.parse
I like JSON mainly because it's so terse. For web content that can be gzipped, this isn't necessarily a big deal (hence why xhtml is so popular). But there are occasions where this can be beneficial.
For example, for one project I was transmitting information that needed to be serialized and transmitted via XMPP. Since most servers will limit the amount of data you can transmit in a single message, I found it helpful to use JSON over the obvious alternative, XML.
As an added bonus, if you're familiar with Python or Javascript, you already pretty much know JSON and can interpret it without much training at all.
What is JSON?
JavaScript Object Notation (JSON) is a lightweight data-interchange format inspired by the object literals of JavaScript.
JSON values can consist of:
objects (collections of name-value pairs)
arrays (ordered lists of values)
strings (in double quotes)
numbers
true, false, or null
JSON is language independent.
JSON with PHP?
After PHP Version 5.2.0, JSON extension is decodes and encodes functionalities as default.
Json_encode - returns the JSON representation of values
Json_decode - Decodes the JSON String
Json_last_error - Returns the last error occured.
JSON Syntax and Rules?
JSON syntax is derived from JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
Sometimes technicality is given where none is required, and while many of the top voted answers are accurately technical and specific, I personally don't think they are any more easy to understand, or succinct, as what can be found on Wikipedia, or in official documentation.
The way I like to think of JSON is exactly what it is - a language within a world of different languages. However, the difference between JSON and other languages is that "everyone" "speaks" JSON, along with their "native language."
Using a real world example, let's pretend we have three people. One person speaks Igbo as their native tongue. The second person would like to interact with the first person, however, the first person speaks Yoruba as their first language.
What can we do?
Thankfully, the third person in our example grew up speaking English, but also happens to speak both Igbo and Yoruba as second languages, and so can act as an intermediary between the first two individuals.
In the programming world, the first "person" is Python, the second "person" is Ruby, and the third "person" is JSON, who just so happens to be able to "translate" Ruby into Python and vice versa! Now obviously this analogy isn't a perfect one, but, as someone who is bilingual, I believe it's an easy way to look at how JSON interacts with other programming languages.
We have to do a project on college and we faced a very big problem, it is called Same Origin Policy. Amog other things, it makes that your XMLHttpRequest method from Javascript can't make requests to domains other than the domain that your site is on.
For example you can't make request to www.otherexample.com if your site is on www.example.com. JSONRequest allows that, but you will get result in JSON format if that site allows that(for example it has a web service that returns messages in JSON).
That is one problem where you could use JSON perhaps.
Here is something practical: Yahoo JSON
The difference between JSON and conventional syntax would be as follows (in Javascript)
Conventional
function Employee(name, Id, Phone, email){
this.name = name;
this.Id = Id;
this.Phone = Phone;
this.email = email;
}
//access or call it as
var Emp = new Employee("mike","123","9373849784","mike.Anderson#office.com");
With JSON
if we use JSON we can define in different way as
function Employee(args){
this.name = args.name;
this.Id = args.Id;
this.Phone = args.Phone;
this.email = args.email;
}
//now access this as...
var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'mike.adnersone#office.com'});
The important thing we have to remember is that, if we have to build the "Employee" class or modal with 100 elements without JSON method we have to parse everything when creating class. But with JSON we can define the objects inline only when a new object for the class is defined.
so this line below is the way of doing things with JSON(just a simple way to define things)
var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'mike.adnersone#office.com'});
It's very simple. JSON stands for Java Script Object Notation. Think of it as an alternative to using XML for transferring data between software components.
For example, I recently wrote a bunch of web services that returned JSON, and some Javascript developers then wrote code which called the services and consumed the information returned in that format.
JSON(Javascript object notation) is a light weight data format for data exchange/transfer. Its in key value pair as the JavaScript is.
For REST API its widely used for data transfer from server to client. Nowadays many of the social media sites are using this. Although I don't see this as robust as XML with respect of data types. XML has very rich datatypes and XSD. JSON is bit lacking in this.
For same amount of string data JSON will be lighter compare to XML as XML has all that opening and closing tags, etc...
In the Java context, one reason why JSON might want to be used, is that it provides a very good alternative to Java's Serialization framework, which has been shown (historically) to be subject to some fairly serious vulnerabilities.
Joshua Bloch discusses this in depth in Item 85 "Prefer Alternatives to Java Serialization" (Effective Java 3rd Edition)
Java's Serialization was initially meant to translate data structures into a format that could be easily transmitted or stored. JSON meets this requirement, without the serious exploits referred to above.
Try the following code to parse your php json response:
read.php
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$.ajax({
url:'index.php',
data:{},
type:"POST",
success:function(result) {
jsondecoded = $.parseJSON(result);
$.each(jsondecoded, function(index, value) {
$("#servers").text($("#servers").text() + " " + value.servername);
console.log(value.start);
console.log(value.end);
console.log(value.id);
});
},
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
</script>
server.php
<?php
echo '[{"start":"2017-08-29","end":"2017-09-01","id":"22"},{"start":"2017-09-03","end":"2017-09-06","id":"23"}]';
?>