SlideShare a Scribd company logo
JSON The Data Transfer Format of the Stars Douglas Crockford Yahoo! Inc.
Data Interchange The key idea in Ajax. An alternative to page replacement. Applications delivered as pages. How should the data be delivered?
History of Data Formats Ad Hoc Database Model Document Model Programming Language Model
JSON JavaScript Object Notation Minimal Textual Subset of JavaScript
JSON A Subset of ECMA-262 Third Edition. Language Independent. Text-based. Light-weight. Easy to parse.
JSON Is Not... JSON is not a document format. JSON is not a markup language. JSON is not a general serialization format. No recursive/recurring structures. No invisible structures. No functions.
History 1999 ECMAScript Third Edition 2001 State Software, Inc. 2002 JSON.org 2005 Ajax
Object Quasi-Literals JavaScript Python NewtonScript
Languages Chinese English French German Italian Japanese Korean
Languages ActionScript C / C++ C# Cold Fusion Delphi E Erlang Java Lisp Perl Objective-C Objective CAML PHP Python Rebol Ruby Scheme Squeak
Values Strings Numbers Booleans Objects Arrays null
Value
Strings Sequence of 0 or more Unicode characters No separate character type A character is represented as a string with a length of 1 Wrapped in  " double quotes " Backslash escapement
String
Numbers Integer Real Scientific No octal or hex No  NaN  or  Infinity   Use  null  instead
Number
Booleans true false
null A value that isn't anything
Object Objects are unordered containers of key/value pairs Objects are wrapped in  { } ,  separates key/value pairs :  separates keys and values Keys are strings  Values are JSON values struct, record, hashtable, object
Object
Object {"name":"Jack B. Nimble","at large": true,"grade":"A","level":3, "format": {"type":"rect","width":1920, "height":1080,"interlace":false, "framerate":24} }
Object { "name":  "Jack B. Nimble",  "at large": true,  "grade":  "A",  "format":  { "type":  "rect",  "width":  1920,  "height":  1080,  "interlace": false,  "framerate": 24 } }
Array Arrays are ordered sequences of values Arrays are wrapped in  [] ,  separates values  JSON does not talk about indexing. An implementation can start array indexing at 0 or 1.
Array
Array ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] [ [0, -1, 0], [1, 0, 0], [0, 0, 1] ]
Arrays vs Objects Use objects when the key names are arbitrary strings. Use arrays when the key names are sequential integers. Don't get confused by the term Associative Array.
Rules A JSON decoder must accept all well-formed JSON text. A JSON decoder may also accept non-JSON text. A JSON encoder must only produce well-formed JSON text. Be conservative in what you do, be liberal in what you accept from others.
MIME Media Type application/json
JSON in Ajax HTML Delivery. JSON data is built into the page. <html>... <script> var data =  { ... JSONdata ... } ;
JSON in Ajax XMLHttpRequest Obtain  responseText Parse the  responseText responseData = eval( '(' +  responseText  + ')'); responseData =  responseText .parseJSON();
JSON in Ajax Secret  <iframe> Request data using  form.submit  to the  <iframe>  target. The server sends the JSON text embedded in a script in a document. <html><head><script> document.domain = 'penzance.com'; parent.deliver( { ... JSONtext ... } ); </script></head></html> The function  deliver  is passed the value.
JSON in Ajax Dynamic script tag hack. Create a script node. The  src  url makes the request. The server sends the JSON text embedded in a script. deliver( { ... JSONtext ... } ); The function  deliver  is passed the value. The dynamic script tag hack is insecure.
JSONRequest A new facility. Two way data interchange between any page and any server. Exempt from the Same Origin Policy. Campaign to make a standard feature of all browsers. http://www.JSON.org/JSONRequest.html
ECMAScript Fourth Ed. New Methods: Array.prototype.toJSONString Object.prototype.toJSONString String.prototype.parseJSON Available now:  JSON.org/json.js
Security Is it safe to use  eval  with XMLHttpRequest? The JSON data comes from the same server that vended the page.  eval  of the data is no less secure than the original html. If in doubt, use  string .parseJSON  instead of  eval .
Never trust the client The client cannot and will not keep our secrets and cannot and will not protect our interests. Do not trust machines not under your absolute control. The server must validate everything the client tells it.
supplant var template = '<table border=&quot; {border} &quot;>' + '<tr><th>Last</th><td> {last} </td></tr>' + '<tr><th>First</th><td> {first} </td></tr>' + '</table>'; var data =  { &quot;first&quot;:  &quot;Carl&quot;,  &quot;last&quot;:  &quot;Hollywood&quot;,  &quot;border&quot;: 2 } ; mydiv.innerHTML = template.supplant(data);
supplant String.prototype.supplant = function (o) {  return this.replace(/{([^{}]*)}/g,  function (a, b) {  var r = o[b]; return typeof r === 'string' ?  r : a;  } );  };
JSONT var rules = {  self:  '<svg>< {closed}  stroke=&quot; {color} &quot; points=&quot; {points} &quot; /></svg>',   closed: function (x) {return x ? 'polygon' : 'polyline';},  'points[*][*]': ' {$}  '  }; var data = { &quot;color&quot;:  &quot;blue&quot;,  &quot;closed&quot;: true,  &quot;points&quot;: [[10,10], [20,10], [20,20], [10,20]] }; jsonT(data, rules)  <svg><polygon stroke=&quot;blue&quot;  points=&quot;10 10 20 10 20 20 10 20 &quot; /></svg>
http://goessner.net/articles/jsont/ function jsonT(self, rules) { var T = {  output: false,  init: function () {  for (var rule in rules) if (rule.substr(0,4) != &quot;self&quot;) rules[&quot;self.&quot; + rule] = rules[rule];  return this;  },  apply: function(expr) {  var trf = function (s) {  return s.replace(/{([A-Za-z0-9_\$\.\[\]\'@\(\)]+)}/g, function ($0, $1){ return T.processArg($1, expr); }) },  x = expr.replace(/\[[0-9]+\]/g, &quot;[*]&quot;),  res;  if (x in rules) {  if (typeof(rules[x]) == &quot;string&quot;) res = trf(rules[x]);  else if (typeof(rules[x]) == &quot;function&quot;) res = trf(rules[x](eval(expr)).toString());  } else res = T.eval(expr);  return res;  },  processArg: function (arg, parentExpr) {  var expand = function (a, e) { return (e = a.replace(/^\$/,e)).substr(0, 4) != &quot;self&quot; ? (&quot;self.&quot; + e) : e;  },  res = &quot;&quot;;  T.output = true;  if (arg.charAt(0) == &quot;@&quot;) res = eval(arg.replace(/@([A-za-z0-9_]+)\(([A-Za-z0-9_\$\.\[\]\']+)\)/, function($0, $1, $2){ return &quot;rules['self.&quot; + $1 + &quot;'](&quot; + expand($2,parentExpr) + &quot;)&quot;; }));  else if (arg != &quot;$&quot;) res = T.apply(expand(arg, parentExpr));  else res = T.eval(parentExpr);  T.output = false;  return res;  },  eval: function (expr) {  var v = eval(expr), res = &quot;&quot;; if (typeof(v) != &quot;undefined&quot;) {  if (v instanceof Array) {  for (var i = 0; i < v.length; i++) if (typeof(v[i]) != &quot;undefined&quot;) res += T.apply(expr + &quot;[&quot; + i + &quot;]&quot;);  } else if (typeof(v) == &quot;object&quot;) {  for (var m in v) if (typeof(v[m]) != &quot;undefined&quot;) res += T.apply(expr+&quot;.&quot;+m);  } else if (T.output) res += v;  }  return res;  }  }; return T.init().apply(&quot;self&quot;);  }
Some features that make  it  well-suited for data transfer It's simultaneously human- and machine-readable format;  It has support for Unicode, allowing almost any information in any human language to be communicated;  The self-documenting format that describes structure and field names as well as specific values;  The strict syntax and parsing requirements that allow the necessary parsing algorithms to remain simple, efficient, and consistent; The ability to represent the most general computer science data structures: records, lists and trees.
JSON Looks Like Data JSON's simple values are the same as used in programming languages. No restructuring is required: JSON's structures look like conventional programming language structures. JSON's  object  is record, struct, object, dictionary, hash, associate array... JSON's  array  is array, vector, sequence, list...
Arguments against JSON JSON Doesn't Have Namespaces. JSON Has No Validator. JSON Is Not Extensible. JSON Is Not XML.
JSON Doesn't Have Namespaces Every object is a namespace. Its set of keys is independent of all other objects, even exclusive of nesting. JSON uses  scope  to avoid ambiguity, just as programming languages do.
Namespace http://www.w3c.org/TR/REC-xml-names/ In this example, there are three occurrences of the name  title  within the markup, and the name alone clearly provides insufficient information to allow correct processing by a software module. <section> < title >Book-Signing Event</ title > <signing> <author  title =&quot;Mr&quot; name=&quot;Vikram Seth&quot; /> <book  title =&quot;A Suitable Boy&quot; price=&quot;$22.95&quot; /> </signing> <signing> <author  title =&quot;Dr&quot; name=&quot;Oliver Sacks&quot; /> <book  title =&quot;The Island of the Color-Blind&quot;  price=&quot;$12.95&quot; /> </signing> </section>
Namespace {&quot;section&quot;: &quot; title &quot;: &quot;Book-Signing Event&quot;, &quot;signing&quot;: [ { &quot;author&quot;: { &quot; title &quot;: &quot;Mr&quot;, &quot;name&quot;: &quot;Vikram Seth&quot; }, &quot;book&quot;: { &quot; title &quot;: &quot;A Suitable Boy&quot;,  &quot;price&quot;: &quot;$22.95&quot; } }, { &quot;author&quot;: { &quot; title &quot;: &quot;Dr&quot;, &quot;name&quot;: &quot;Oliver Sacks&quot; }, &quot;book&quot;: { &quot; title &quot;: &quot;The Island of the Color-Blind&quot;,  &quot;price&quot;: &quot;$12.95&quot; } } ] }} section.title section.signing[0].author.title section.signing[1].book.title
JSON Has No Validator Being well-formed and valid is not the same as being correct and relevant. Ultimately, every application is responsible for validating its inputs. This cannot be delegated. A YAML validator can be used.
JSON is Not Extensible It does not need to be.  It can represent any non-recurrent data structure as is. JSON is flexible. New fields can be added to existing structures without obsoleting existing programs.
Versionless JSON has no version number. No revisions to the JSON grammar are anticipated. JSON is very stable.
Supersets YAML is a superset of JSON. A YAML decoder is a JSON decoder. JavaScript is a superset of JSON. A JavaScript compiler is a JSON decoder. JSONIC is a programming language based on JSON.
JSON Is Not XML objects arrays strings numbers booleans null element attribute attribute string content <![CDATA[ ]]> entities declarations schema stylesheets comments version namespace
Data Interchange JSON is a simple, common representation of data. Communication between servers and browser clients. Communication between peers. Language independent data interchange.
Why the Name? XML is not a good data serialization format, but it is a document standard. Having a standard to refer to eliminates a lot of squabbling.
JSLint JSLint can help improve the robustness and portability of your programs. It enforces style rules. It can spot some errors that are very difficult to find in debugging. It can help eliminate implied globals. Currently available on the web and as a Konfabulator widget. Soon, in text editors and Eclipse.
JSLint Warning: JSLint will hurt your feelings. If you follow its advice, JSLint will make your programs better. http://www.JSLint.com/
www.JSON.org

More Related Content

PDF
Intro to JSON
PPT
JavaScript Object Notation (JSON)
PDF
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
PPTX
Intro to JSON
JavaScript Object Notation (JSON)
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...

What's hot (20)

DOCX
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
PPT
Java Script Object Notation (JSON)
PPT
java script json
PDF
Json
PDF
Introduction to JSON
PPT
JSON - Quick Overview
PPTX
JSON(JavaScript Object Notation)
PDF
06. ElasticSearch : Mapping and Analysis
PDF
08. ElasticSearch : Sorting and Relevance
PPT
KEY
MongoMapper lightning talk
PDF
Json at work overview and ecosystem-v2.0
PPT
RESTful JSON web databases
PDF
Basics of JSON (JavaScript Object Notation) with examples
PDF
JSON and MongoDB in R
PDF
Mongo learning series
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
Java Script Object Notation (JSON)
java script json
Json
Introduction to JSON
JSON - Quick Overview
JSON(JavaScript Object Notation)
06. ElasticSearch : Mapping and Analysis
08. ElasticSearch : Sorting and Relevance
MongoMapper lightning talk
Json at work overview and ecosystem-v2.0
RESTful JSON web databases
Basics of JSON (JavaScript Object Notation) with examples
JSON and MongoDB in R
Mongo learning series
Ad

Viewers also liked (20)

PDF
Techday Arrow Group: Delphi Xe5 Android - une approche par la 3D
KEY
Douglas Crockford - Programming Style and Your Brain
PDF
Performance, Games, and Distributed Testing in JavaScript
PPT
The JSON Saga
PPT
Ajax Performance
PPT
The Theory Of The Dom
PPTX
Introduction to JSON & AJAX
PDF
Performance Improvements in Browsers
PPT
Douglas Crockford - Ajax Security
PDF
Building a JavaScript Library
PPT
OOP in JavaScript
PDF
Good Parts of JavaScript Douglas Crockford
PPT
Advanced Javascript
PPTX
Advanced JavaScript Concepts
ODP
R-Users Group JSON and ReST Introduction using Twitter
PPS
Exposé MSAP
PPTX
Formation Réseaux Sociaux Facebook, Linkedin Twitter
PDF
Scalable JavaScript Application Architecture
PPTX
JSON: The Basics
PDF
The DOM is a Mess @ Yahoo
Techday Arrow Group: Delphi Xe5 Android - une approche par la 3D
Douglas Crockford - Programming Style and Your Brain
Performance, Games, and Distributed Testing in JavaScript
The JSON Saga
Ajax Performance
The Theory Of The Dom
Introduction to JSON & AJAX
Performance Improvements in Browsers
Douglas Crockford - Ajax Security
Building a JavaScript Library
OOP in JavaScript
Good Parts of JavaScript Douglas Crockford
Advanced Javascript
Advanced JavaScript Concepts
R-Users Group JSON and ReST Introduction using Twitter
Exposé MSAP
Formation Réseaux Sociaux Facebook, Linkedin Twitter
Scalable JavaScript Application Architecture
JSON: The Basics
The DOM is a Mess @ Yahoo
Ad

Similar to Json (20)

PPT
OSS BarCamp Mumbai - JSON Presentation and Demo
PPT
Zend framework 05 - ajax, json and j query
PPT
J s-o-n-120219575328402-3
PDF
Json the-x-in-ajax1588
PPT
json.ppt download for free for college project
PPT
Douglas Crockford Presentation Jsonsaga
PDF
ApacheCon 2000 Everything you ever wanted to know about XML Parsing
PPT
Sax Dom Tutorial
PDF
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
PPT
Jsonsaga
PPT
O9schema
PPT
Schema
PPT
2310 b 12
PPT
Pxb For Yapc2008
PPT
PPT
Processing XML with Java
ODP
JavaScript and jQuery Fundamentals
PPT
Lecture 4 - Comm Lab: Web @ ITP
PPT
The JavaScript Programming Language
PPT
Javascript by Yahoo
OSS BarCamp Mumbai - JSON Presentation and Demo
Zend framework 05 - ajax, json and j query
J s-o-n-120219575328402-3
Json the-x-in-ajax1588
json.ppt download for free for college project
Douglas Crockford Presentation Jsonsaga
ApacheCon 2000 Everything you ever wanted to know about XML Parsing
Sax Dom Tutorial
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
Jsonsaga
O9schema
Schema
2310 b 12
Pxb For Yapc2008
Processing XML with Java
JavaScript and jQuery Fundamentals
Lecture 4 - Comm Lab: Web @ ITP
The JavaScript Programming Language
Javascript by Yahoo

More from elliando dias (20)

PDF
Clojurescript slides
PDF
Why you should be excited about ClojureScript
PDF
Functional Programming with Immutable Data Structures
PPT
Nomenclatura e peças de container
PDF
Geometria Projetiva
PDF
Polyglot and Poly-paradigm Programming for Better Agility
PDF
Javascript Libraries
PDF
How to Make an Eight Bit Computer and Save the World!
PDF
Ragel talk
PDF
A Practical Guide to Connecting Hardware to the Web
PDF
Introdução ao Arduino
PDF
Minicurso arduino
PDF
Incanter Data Sorcery
PDF
PDF
Fab.in.a.box - Fab Academy: Machine Design
PDF
The Digital Revolution: Machines that makes
PDF
Hadoop + Clojure
PDF
Hadoop - Simple. Scalable.
PDF
Hadoop and Hive Development at Facebook
PDF
Multi-core Parallelization in Clojure - a Case Study
Clojurescript slides
Why you should be excited about ClojureScript
Functional Programming with Immutable Data Structures
Nomenclatura e peças de container
Geometria Projetiva
Polyglot and Poly-paradigm Programming for Better Agility
Javascript Libraries
How to Make an Eight Bit Computer and Save the World!
Ragel talk
A Practical Guide to Connecting Hardware to the Web
Introdução ao Arduino
Minicurso arduino
Incanter Data Sorcery
Fab.in.a.box - Fab Academy: Machine Design
The Digital Revolution: Machines that makes
Hadoop + Clojure
Hadoop - Simple. Scalable.
Hadoop and Hive Development at Facebook
Multi-core Parallelization in Clojure - a Case Study

Recently uploaded (20)

PPTX
Cloud computing and distributed systems.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Electronic commerce courselecture one. Pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Machine learning based COVID-19 study performance prediction
PPTX
A Presentation on Artificial Intelligence
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
Cloud computing and distributed systems.
Diabetes mellitus diagnosis method based random forest with bat algorithm
Electronic commerce courselecture one. Pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
20250228 LYD VKU AI Blended-Learning.pptx
Machine learning based COVID-19 study performance prediction
A Presentation on Artificial Intelligence
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
“AI and Expert System Decision Support & Business Intelligence Systems”
Digital-Transformation-Roadmap-for-Companies.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Chapter 3 Spatial Domain Image Processing.pdf
Encapsulation theory and applications.pdf
Empathic Computing: Creating Shared Understanding
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Advanced methodologies resolving dimensionality complications for autism neur...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Building Integrated photovoltaic BIPV_UPV.pdf

Json

  • 1. JSON The Data Transfer Format of the Stars Douglas Crockford Yahoo! Inc.
  • 2. Data Interchange The key idea in Ajax. An alternative to page replacement. Applications delivered as pages. How should the data be delivered?
  • 3. History of Data Formats Ad Hoc Database Model Document Model Programming Language Model
  • 4. JSON JavaScript Object Notation Minimal Textual Subset of JavaScript
  • 5. JSON A Subset of ECMA-262 Third Edition. Language Independent. Text-based. Light-weight. Easy to parse.
  • 6. JSON Is Not... JSON is not a document format. JSON is not a markup language. JSON is not a general serialization format. No recursive/recurring structures. No invisible structures. No functions.
  • 7. History 1999 ECMAScript Third Edition 2001 State Software, Inc. 2002 JSON.org 2005 Ajax
  • 8. Object Quasi-Literals JavaScript Python NewtonScript
  • 9. Languages Chinese English French German Italian Japanese Korean
  • 10. Languages ActionScript C / C++ C# Cold Fusion Delphi E Erlang Java Lisp Perl Objective-C Objective CAML PHP Python Rebol Ruby Scheme Squeak
  • 11. Values Strings Numbers Booleans Objects Arrays null
  • 12. Value
  • 13. Strings Sequence of 0 or more Unicode characters No separate character type A character is represented as a string with a length of 1 Wrapped in &quot; double quotes &quot; Backslash escapement
  • 15. Numbers Integer Real Scientific No octal or hex No NaN or Infinity Use null instead
  • 18. null A value that isn't anything
  • 19. Object Objects are unordered containers of key/value pairs Objects are wrapped in { } , separates key/value pairs : separates keys and values Keys are strings Values are JSON values struct, record, hashtable, object
  • 21. Object {&quot;name&quot;:&quot;Jack B. Nimble&quot;,&quot;at large&quot;: true,&quot;grade&quot;:&quot;A&quot;,&quot;level&quot;:3, &quot;format&quot;: {&quot;type&quot;:&quot;rect&quot;,&quot;width&quot;:1920, &quot;height&quot;:1080,&quot;interlace&quot;:false, &quot;framerate&quot;:24} }
  • 22. Object { &quot;name&quot;: &quot;Jack B. Nimble&quot;, &quot;at large&quot;: true, &quot;grade&quot;: &quot;A&quot;, &quot;format&quot;: { &quot;type&quot;: &quot;rect&quot;, &quot;width&quot;: 1920, &quot;height&quot;: 1080, &quot;interlace&quot;: false, &quot;framerate&quot;: 24 } }
  • 23. Array Arrays are ordered sequences of values Arrays are wrapped in [] , separates values JSON does not talk about indexing. An implementation can start array indexing at 0 or 1.
  • 24. Array
  • 25. Array [&quot;Sunday&quot;, &quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot;, &quot;Friday&quot;, &quot;Saturday&quot;] [ [0, -1, 0], [1, 0, 0], [0, 0, 1] ]
  • 26. Arrays vs Objects Use objects when the key names are arbitrary strings. Use arrays when the key names are sequential integers. Don't get confused by the term Associative Array.
  • 27. Rules A JSON decoder must accept all well-formed JSON text. A JSON decoder may also accept non-JSON text. A JSON encoder must only produce well-formed JSON text. Be conservative in what you do, be liberal in what you accept from others.
  • 28. MIME Media Type application/json
  • 29. JSON in Ajax HTML Delivery. JSON data is built into the page. <html>... <script> var data = { ... JSONdata ... } ;
  • 30. JSON in Ajax XMLHttpRequest Obtain responseText Parse the responseText responseData = eval( '(' + responseText + ')'); responseData = responseText .parseJSON();
  • 31. JSON in Ajax Secret <iframe> Request data using form.submit to the <iframe> target. The server sends the JSON text embedded in a script in a document. <html><head><script> document.domain = 'penzance.com'; parent.deliver( { ... JSONtext ... } ); </script></head></html> The function deliver is passed the value.
  • 32. JSON in Ajax Dynamic script tag hack. Create a script node. The src url makes the request. The server sends the JSON text embedded in a script. deliver( { ... JSONtext ... } ); The function deliver is passed the value. The dynamic script tag hack is insecure.
  • 33. JSONRequest A new facility. Two way data interchange between any page and any server. Exempt from the Same Origin Policy. Campaign to make a standard feature of all browsers. http://www.JSON.org/JSONRequest.html
  • 34. ECMAScript Fourth Ed. New Methods: Array.prototype.toJSONString Object.prototype.toJSONString String.prototype.parseJSON Available now: JSON.org/json.js
  • 35. Security Is it safe to use eval with XMLHttpRequest? The JSON data comes from the same server that vended the page. eval of the data is no less secure than the original html. If in doubt, use string .parseJSON instead of eval .
  • 36. Never trust the client The client cannot and will not keep our secrets and cannot and will not protect our interests. Do not trust machines not under your absolute control. The server must validate everything the client tells it.
  • 37. supplant var template = '<table border=&quot; {border} &quot;>' + '<tr><th>Last</th><td> {last} </td></tr>' + '<tr><th>First</th><td> {first} </td></tr>' + '</table>'; var data = { &quot;first&quot;: &quot;Carl&quot;, &quot;last&quot;: &quot;Hollywood&quot;, &quot;border&quot;: 2 } ; mydiv.innerHTML = template.supplant(data);
  • 38. supplant String.prototype.supplant = function (o) { return this.replace(/{([^{}]*)}/g, function (a, b) { var r = o[b]; return typeof r === 'string' ? r : a; } ); };
  • 39. JSONT var rules = { self: '<svg>< {closed} stroke=&quot; {color} &quot; points=&quot; {points} &quot; /></svg>', closed: function (x) {return x ? 'polygon' : 'polyline';}, 'points[*][*]': ' {$} ' }; var data = { &quot;color&quot;: &quot;blue&quot;, &quot;closed&quot;: true, &quot;points&quot;: [[10,10], [20,10], [20,20], [10,20]] }; jsonT(data, rules) <svg><polygon stroke=&quot;blue&quot; points=&quot;10 10 20 10 20 20 10 20 &quot; /></svg>
  • 40. http://goessner.net/articles/jsont/ function jsonT(self, rules) { var T = { output: false, init: function () { for (var rule in rules) if (rule.substr(0,4) != &quot;self&quot;) rules[&quot;self.&quot; + rule] = rules[rule]; return this; }, apply: function(expr) { var trf = function (s) { return s.replace(/{([A-Za-z0-9_\$\.\[\]\'@\(\)]+)}/g, function ($0, $1){ return T.processArg($1, expr); }) }, x = expr.replace(/\[[0-9]+\]/g, &quot;[*]&quot;), res; if (x in rules) { if (typeof(rules[x]) == &quot;string&quot;) res = trf(rules[x]); else if (typeof(rules[x]) == &quot;function&quot;) res = trf(rules[x](eval(expr)).toString()); } else res = T.eval(expr); return res; }, processArg: function (arg, parentExpr) { var expand = function (a, e) { return (e = a.replace(/^\$/,e)).substr(0, 4) != &quot;self&quot; ? (&quot;self.&quot; + e) : e; }, res = &quot;&quot;; T.output = true; if (arg.charAt(0) == &quot;@&quot;) res = eval(arg.replace(/@([A-za-z0-9_]+)\(([A-Za-z0-9_\$\.\[\]\']+)\)/, function($0, $1, $2){ return &quot;rules['self.&quot; + $1 + &quot;'](&quot; + expand($2,parentExpr) + &quot;)&quot;; })); else if (arg != &quot;$&quot;) res = T.apply(expand(arg, parentExpr)); else res = T.eval(parentExpr); T.output = false; return res; }, eval: function (expr) { var v = eval(expr), res = &quot;&quot;; if (typeof(v) != &quot;undefined&quot;) { if (v instanceof Array) { for (var i = 0; i < v.length; i++) if (typeof(v[i]) != &quot;undefined&quot;) res += T.apply(expr + &quot;[&quot; + i + &quot;]&quot;); } else if (typeof(v) == &quot;object&quot;) { for (var m in v) if (typeof(v[m]) != &quot;undefined&quot;) res += T.apply(expr+&quot;.&quot;+m); } else if (T.output) res += v; } return res; } }; return T.init().apply(&quot;self&quot;); }
  • 41. Some features that make it well-suited for data transfer It's simultaneously human- and machine-readable format; It has support for Unicode, allowing almost any information in any human language to be communicated; The self-documenting format that describes structure and field names as well as specific values; The strict syntax and parsing requirements that allow the necessary parsing algorithms to remain simple, efficient, and consistent; The ability to represent the most general computer science data structures: records, lists and trees.
  • 42. JSON Looks Like Data JSON's simple values are the same as used in programming languages. No restructuring is required: JSON's structures look like conventional programming language structures. JSON's object is record, struct, object, dictionary, hash, associate array... JSON's array is array, vector, sequence, list...
  • 43. Arguments against JSON JSON Doesn't Have Namespaces. JSON Has No Validator. JSON Is Not Extensible. JSON Is Not XML.
  • 44. JSON Doesn't Have Namespaces Every object is a namespace. Its set of keys is independent of all other objects, even exclusive of nesting. JSON uses scope to avoid ambiguity, just as programming languages do.
  • 45. Namespace http://www.w3c.org/TR/REC-xml-names/ In this example, there are three occurrences of the name title within the markup, and the name alone clearly provides insufficient information to allow correct processing by a software module. <section> < title >Book-Signing Event</ title > <signing> <author title =&quot;Mr&quot; name=&quot;Vikram Seth&quot; /> <book title =&quot;A Suitable Boy&quot; price=&quot;$22.95&quot; /> </signing> <signing> <author title =&quot;Dr&quot; name=&quot;Oliver Sacks&quot; /> <book title =&quot;The Island of the Color-Blind&quot; price=&quot;$12.95&quot; /> </signing> </section>
  • 46. Namespace {&quot;section&quot;: &quot; title &quot;: &quot;Book-Signing Event&quot;, &quot;signing&quot;: [ { &quot;author&quot;: { &quot; title &quot;: &quot;Mr&quot;, &quot;name&quot;: &quot;Vikram Seth&quot; }, &quot;book&quot;: { &quot; title &quot;: &quot;A Suitable Boy&quot;, &quot;price&quot;: &quot;$22.95&quot; } }, { &quot;author&quot;: { &quot; title &quot;: &quot;Dr&quot;, &quot;name&quot;: &quot;Oliver Sacks&quot; }, &quot;book&quot;: { &quot; title &quot;: &quot;The Island of the Color-Blind&quot;, &quot;price&quot;: &quot;$12.95&quot; } } ] }} section.title section.signing[0].author.title section.signing[1].book.title
  • 47. JSON Has No Validator Being well-formed and valid is not the same as being correct and relevant. Ultimately, every application is responsible for validating its inputs. This cannot be delegated. A YAML validator can be used.
  • 48. JSON is Not Extensible It does not need to be. It can represent any non-recurrent data structure as is. JSON is flexible. New fields can be added to existing structures without obsoleting existing programs.
  • 49. Versionless JSON has no version number. No revisions to the JSON grammar are anticipated. JSON is very stable.
  • 50. Supersets YAML is a superset of JSON. A YAML decoder is a JSON decoder. JavaScript is a superset of JSON. A JavaScript compiler is a JSON decoder. JSONIC is a programming language based on JSON.
  • 51. JSON Is Not XML objects arrays strings numbers booleans null element attribute attribute string content <![CDATA[ ]]> entities declarations schema stylesheets comments version namespace
  • 52. Data Interchange JSON is a simple, common representation of data. Communication between servers and browser clients. Communication between peers. Language independent data interchange.
  • 53. Why the Name? XML is not a good data serialization format, but it is a document standard. Having a standard to refer to eliminates a lot of squabbling.
  • 54. JSLint JSLint can help improve the robustness and portability of your programs. It enforces style rules. It can spot some errors that are very difficult to find in debugging. It can help eliminate implied globals. Currently available on the web and as a Konfabulator widget. Soon, in text editors and Eclipse.
  • 55. JSLint Warning: JSLint will hurt your feelings. If you follow its advice, JSLint will make your programs better. http://www.JSLint.com/