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"}]';
?>
Related
Chrome Developer Console is console.loging this:
Your JSON sent is>> {yourVariable: "nothing yet"}
So i know the value "nothing yet" in the {yourVariable: "nothing yet"} JSON object is a string. But how do I know the type of the key yourVariable?
Is there a way how to find that out using the Chrome console only?
All object keys are strings with quotes or without quotes. Try this way to see it. May be you are confused with console print because console print it without quotes and we usually write with quotes.
var jsonObj = {person:"me","age":"30", 123:"123"};
Object.keys(jsonObj).forEach(function(key){
console.log(typeof key)}
);
I have a slightly different take on this question which does not invalidate the comments or answer that you received, but is worth considering.
Because you are talking about JSON, there is no intrinsic datatype in your example. As stated on the JSON.org page:
JSON (JavaScript Object Notation) is a lightweight data-interchange
format. It is easy for humans to read and write. It is easy for
machines to parse and generate.
The point is, that there is a difference between JSON, which is a representation of javascript objects, arrays etc., and variables of those types in javascript.
If you remind yourself that JSON is a form of serialization it makes a lot more sense. Javascript objects for example, can include functions, but a javascript function is not a portable thing, so in rendering some JSON from a javascript object, it is up to the language creating the JSON to do whatever it it needs to in order to convert the data it needs to represent, and that may include simplification and in many cases removal of elements that are incompatible JSON.
The other thing to keep in mind, is that all modern languages have functions or libraries that can parse JSON and turn them into variables or objects that work in those languages. In doing so, they have arguments that can completely change the way the JSON is converted back into instance variables.
For example, in PHP you can choose to have the JSON create one or more PHP objects, or an array of php variables.
In summary, JSON doesn't have variables with datatypes at all. It is a representation of data, that is portable across languages, but the languages must decode the JSON and create objects or variables that are valid in their own runtime.
I have java library that runs webservices and these return a response in XML. The webservices all revolve around giving a list of details about items. Recently, changes were made to allow the services to return JSON by simply converting the XML to JSON. When looking at the responses, I saw they're not as easy to parse as I thought. For example, a webservice that returns details about items.
If there are no items, the returned JSON is as follows:
{"ItemResponse":""}
If there is 1 item, the response is as follows (now itemResponse has a object as value instead of a string):
{"ItemResponse":{"Items":{"Name":"Item1","Cost":"$5"}}}
If there two or more items, the response is (now items has an array as value instead of an object):
{"ItemResponse":{"Items":[{"Name":"Item1","Cost":"$5"},{"Name":"Item2","Cost":"$3"}]}}
To parse these you need several if/else which I think are clunky.
Would it be an improvement if the responses were:
0 items: []
1 item: [{"Name":"Item1","Cost":"$5"}]
2 items: [{"Name":"Item1","Cost":"$5"},{"Name":"Item2","Cost":"$3"}]
This way there is always an array, and it contains the itemdata. An extra wrapper object is possible:
0 items: {"Items":[]}
1 item: {"Items":[{"Name":"Item1","Cost":"$5"}]}
2 items: {"Items":[{"Name":"Item1","Cost":"$5"},{"Name":"Item2","Cost":"$3"}]}
I'm not experienced in JSON so my question is, if you were a developer having to use these webservices, how would you expect the JSON resonse to be formatted? Is it better to always return a consistent array, even if there are no items or is this usually not important? Or is an array not enough and do you really expect a wrapper object around the array?
What are conventions/standards regarding this?
Don't switch result types, always return an array if there are more items possible. Do not mix, for 1 item an object for more an array. That's not a good idea.
Another best practise is that you should version your API. Use something like yoursite.com/api/v1/endpoint. If you don't do this and you change the response of your API. All your client apps will break. So keep this in mind together with documentation. (I've seen this happen a lot in the past..)
As a developer I personally like your second approach, but again it's a preference. There is no standard for this.
There are several reasons to use json:
much more dense and compact: thus data sent is less
in javascript you can directly access those properties without parsing anything. this means you could convert it into an object read the attributes (often used for AJAX)
also in java you usually don't need to parse the json by yourself - there are several nice libs like www.json.org/java/index.html
if you need to know how json is build ... use google ... there tons of infos.
To your actual questions:
for webservices you often could choose between xml and json as a "consumer" try:
https://maps.googleapis.com/maps/api/place/textsearch/json
and
https://maps.googleapis.com/maps/api/place/textsearch/xml
there is no need to format json visually - is it not meant for reading like xml
if your response doesn't have a result, json-service often still is giving a response text - look again at the upper google map links - those are including a response status which makes sense as it is a service.
Nevertheless it's the question if it is worth converting from xml to json if there isn't a specific requirement. As Dieter mentioned: it depends on who is already using this service and how they are consumed ... which means the surrounding environment is very important.
I am attempting to consume an API that I do not have control over which is somewhat poorly documentented and somewhat inconsistent. This means that sometimes, the API returns a different type than what is documented or what you would normally see. For this example, we'll look at a case when an array was returned in a place where I would normally see a string. That makes a crappy API, but my real problem is: How can I more easily track those things down? Right now, the errors look something like this:
No usable value for identifier
Do not know how to convert JArray(List(JString(3c8723eceb1a), JString(cba8849e7a2f))) into class java.lang.String
After deciphering the problem (why JValue::toString doesn't emit a JSON string is utterly perplexing to me), I can figure out the API returned an array when I made my case class only able to deal with Strings. Great. My issue is that finding this discrepancy between my object model and the contents of the JSON seems significantly more difficult than it should be.
Currently, this is my workflow for hunting down decoding errors:
Hope bad data has some sort of identifying marker. If this is not true, then it is way more guesswork and you will have to repeat the following steps for each entry that looks like the bad bits.
Go through the troubles of converting the JArray(List(JString(...), ...)) from the error message into valid JSON, hoping that I encode JSON the same way at the API endpoint I got the data from does. If this is not true, then I use a JSON formatter (jq) to format all data consistently.
Locate the place in the source data where the decoding error originates from.
Backtrack through arrays and objects to discover how I need to change my object model to more accurately represent what data is coming back to me from the API.
Some background: I'm coming from C++, where I rolled my own JSON deserialization framework for this purpose. The equivalent error when using the library I built is:
Error decoding value at result.taskInstances[914].subtasks[5].identifier: expected std::string but found array value (["3c8723eceb1a","cba8849e7a2f"]) at 1:4084564
This is my process when using my hand-rolled library:
Look at the expected type (std::string) compared with the data that was actually found (["3c8723eceb1a","cba8849e7a2f"]) and alter my data model for the path for the data in the source (result.taskInstances[914].subtasks[5].identifier)
As you can see, I get to jump immediately to the problem that I actually have.
My question is: Is there a way to more quickly debug inconsistencies between my data model and the results I'm getting back from the API?
I'm using json4s-native_2.10 version 3.2.8.
A simplified example:
{ "property": ["3c8723eceb1a", "cba8849e7a2f"] }
Does not mesh with Scala class:
case class Thing(property: String)
The best solution would be to use Try http://www.scala-lang.org/api/current/#scala.util.Try in Scala, but unfortunately json4s API cannot.
So, I think you should use Scala Option type http://www.scala-lang.org/api/current/#scala.Option .
In Scala, and more generally in functional languages, Options are used to represent an object that can be there or not (like à nil value).
For handle parsing failures, you can use parse(str).toOption, which is a function that return an Option[JValue], and you can doing a pattern matching on the resulting value.
For handling extraction of data extraction into case classes, you can use extractOpt function, to do pattern matching on the value.
You can read this answer : https://stackoverflow.com/a/15944506/2330361
All over the net I see examples of using jQuery to make AJAX POSTs of JSON encoded data to a server. What is the point of encoding the data in JSONfirst? Why not just send it as the default data type application/x-www-url-form-encoded which would save having to parse JSON data on the server?
Couple of reasons. One, it's very easy to turn a JavaScript object into JSON, while it takes effort to encode it as x-www-url-form-encoded. Also, x-www-url-form-encoded isn't really used that much any more. Besides the couple of input types that require a form, most things use AJAX nowadays. Also, JSON is much easier to debug because it's legible.
First, you don't have to use json. If you are more comfortable using any other format, then use it.
But keep in mind, it's all strings. And sometimes it makes sense to use a format like JSON. What happens if you form is dynamic, and you enter multiple instances of the same thing (e.g. name1, name2, name3....)? It's really easy to iterate over such things with JSON. And JSON parsers are readily available for all platforms, so it's not like using it is a hinderance on any platforms. Plus, if both submissions and responses use the same format, there is the benefit of consistency for the data in requests and responses.
JSON is short for JavaScript Object Notation, and is a way to store information in an organized, easy-to-access manner.In a nutshell, it gives us a human-readable collection of data that we can access in a really logical manner.
We use JSON encoding to organize stored information.
Example:
var jason = {
"age" : "24",
"hometown" : "Missoula, MT",
"gender" : "male"
};
To access the information stored in json, we can simply refer to the name of the property we need.
Result:
document.write('Json is ' json.age); // Output: Jason is 24
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.