JSON – JavaScript Object Notation
Some of the slides taken from / Paypal Inc.
Copyright 2008-2022 E. Horowitz, M. Papa 1
Copyright By PowCoder代写 加微信 powcoder
What is JSON
• JSON, short for JavaScript Object Notation, is a lightweight data interchange format.
– It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects).
• The JSON format is specified in RFC 4627 (July 2006) authored by .
– https://tools.ietf.org/rfc/rfc4627.txt
– The official MIME type for JSON is application/json. The JSON file extension is
• The JSON format is often used for transmitting structured data over a network connection in a process called serialization.
– Its main application is in Ajax web application programming, where it serves as an alternative to the use of the XML format.
• Code for parsing and generating JSON data is readily available for a large variety of programming languages. The www.json.org website provides a comprehensive listing of existing JSON bindings, organized by language.
Copyright 2008-2022 E. Horowitz, M. Papa 2
Brief History
• JSON was based on a subset of the JavaScript programming language (specifically, Standard ECMA-262 – now in its 12th Edition)
– however, it is a language-independent data format.
– For the complete specification see https://www.ecma-international.org/publications/standards/Ecma-262.htm
The JavaScript ECMA standard is based upon Netscape’s JavaScript and Microsoft’s Jscript
• was the original developer of JSON while he was at State Software, Inc. He is now Senior JavaScript Architect at Paypal
• http://www.json.org/, is a website devoted to JSON discussions and includes many JSON parsers
Copyright 2008-2022 E. Horowitz, M. Papa 3
How to use the JSON format • A JSON file allows one to load data from the server or to send data to it.
• Working with JSON involves three steps: (i) the browser processing, (ii) the server processing, and (iii) the data exchange between them.
1. Client side (browser)
• The content of a JSON file (or stream), or the definition of JSON data is assigned to a variable, and this variable becomes an object of the program.
2. Server side
• a JSON file (or stream) on the server can be operated upon by various programming languages, including PHP and Java thanks to parsers that process the file and may even convert it into classes and attributes of the language.
3. Data exchange
• Loading a JSON file from the server may be accomplished in JavaScript in several ways: – directly including the file into the HTML page, as a JavaScript .json external file.
– loading by a JavaScript command – using XMLHttpRequest()
• To convert JSON into an object, it can be passed to the JavaScript eval() function.
• Sending the file to the server may be accomplished by XMLHttpRequest(). The file is sent
as a text file and processed by the parser of the programming language that uses it.
Copyright 2008-2022 E. Horowitz, M. Papa 4
JSON and XMLHttpRequest Example
• XMLHttpRequest will be covered in more detail in the AJAX lecture
• The XMLHttpRequest code:
var req = new XMLHttpRequest();
req.open(“GET”, “file.json”, true); // “asynchronous” operation req.onreadystatechange = myCode; // the callback req.send(null);
• The JavaScript callback: eval() parses JSON, creates an object and assigns it to variable doc function myCode() {
if (req.readyState == 4) { if (req.Status == 200) {
var doc = eval(‘(‘ + req.responseText + ‘)’); }
• Using the data:
var menuName = doc.getElementById(‘menu’); // finding a field menu doc.menu.value = “my name is”; // assigning a value to the field
• How to access data:
doc.commands[0].title // read value of the “title” field in the array doc.commands[0].action // read value of the “action” field in the array
Copyright 2008-2022 E. Horowitz, M. Papa 5
JavaScript eval()
• The JavaScript eval() is a function property of the Global Object, and evaluates a string
and executes it as if it was JavaScript code, e.g.
• produces the output 200
• Because JSON-formatted text is also syntactically legal JavaScript code, an easy way for a JavaScript program to parse JSON-formatted data is to use the built-in JavaScript eval() function
• the JavaScript interpreter itself is used to execute the JSON data to produce native JavaScript objects.
• The eval() technique is subject to security vulnerabilities if the data and the entire JavaScript environment is not within the control of a single trusted source; See:
• https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval Copyright 2008-2022 E. Horowitz, M. Papa 6
JSON Basic Data Types
• String(double-quotedunicodewithbackslash escaping)
• Numbers(integer,real,orfloatingpoint)
• Booleans(trueandfalse)
• Object(collectionofkey:valuepairs,comma- separated and enclosed in curly brackets)
• Array(anorderedsequenceofvalues,comma- separated and enclosed in square brackets)
• Null(avaluethatisn’tanything)
Copyright 2008-2022 E. Horowitz, M. Papa 7
• Sequenceof0ormoreUnicodecharacters • Noseparatecharactertype
– A character is represented as a string with a length of 1
• Wrappedin”doublequotes” • Backslashescapement
Copyright 2008-2022 E. Horowitz, M. Papa 8
• Objectsareunorderedcontainersofkey/valuepairs
• Objectsarewrappedin{}
• ,separateskey/valuepairs
• :separateskeysandvalues
• Keysarestrings(unlikeinJavaScript)
• ValuesareJSONvalues
• Canbeusedtorepresentstruct,record,hashtable, object
Copyright 2008-2022 E. Horowitz, M. Papa 9
Example Object
{“name”:” . Nimble”,”at large”:
true,”grade”:”A”,”level”:3,
“format”:{“type”:”rect”,”width”:1920,
“height”:1080,”interlace”:false,
“framerate”:24}}
Copyright 2008-2022 E. Horowitz, M. Papa 10
Example Object Formatted
“name”: ” . Nimble”, “at large”: true,
“grade”: “A”,
“level”: 3,
“format”: {
“type”: “rect”,
“width”: 1920,
“height”: 1080,
“interlace”: false,
“framerate”: 24
Copyright 2008-2022 E. Horowitz, M. Papa 11
• Arraysareorderedsequencesofvalues
• Arrays are wrapped in [ ] (square brackets)
• ,separatesvalues
• JSONdoesnottalkaboutindexing.
– An implementation can start array indexing at 0 or 1.
Copyright 2008-2022 E. Horowitz, M. Papa 12
Two Examples of JSON Arrays
• One dimensional
[“Sunday”, “Monday”, “Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday”]
• Two dimensional [
[0, -1, 0],
[1, 0, 0],
Copyright 2008-2022 E. Horowitz, M. Papa 13
Arrays vs Objects
• Use objects when the key names are arbitrary strings
• Use arrays when the key names are sequential integers
Copyright 2008-2022 E. Horowitz, M. Papa 14
JSON is Not XML JSON XML
• Booleans
• attribute
• Attribute string • content
•
• Entities
• Declarations
• Stylesheets
• Comments
• namespace
Copyright 2008-2022 E. Horowitz, M. Papa 15
JSON vs. XML Example
XML Equivalent
“menu”: “File”, “commands”: [
“title”: “New”, “action”:”CreateDoc”
“title”: “Open”, “action”: “OpenDoc”
“title”: “Close”, “action”: “CloseDoc”
Copyright 2008-2022 E. Horowitz, M. Papa 16
Rules for JSON Parsers
• 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
• A list of decoders for JSON can be found at http://www.json.org/
JSON parsers for programming languages include C, C++,
C#, Java, JavaScript, Perl, PHP
Copyright 2008-2022 E. Horowitz, M. Papa 17
Same Origin Policy
• Same origin policy is a security feature that browsers apply to client-side scripts
• It prevents a document or script loaded from one “origin” from getting or setting properties of a document from a different “origin”
– Rationale: the browser should not trust content loaded from arbitrary websites • Given the URL: http://www.example.com/dir/page.html
http://www.example.com/dir2/other.json
http://www.example.com/dir/inner/other.json
http://www.example.com:81/dir2/other.json
https://www.example.com/dir2/other.json
http://en.example.com/dir2/other.json http://example.com/dir2/other.json
Success Success Failure Failure
Same protocol and host
Same protocol and host
Same protocol and host but different port
Different protocol
Different host
Different host
Copyright 2008-2022 E. Horowitz, M. Papa 18
JSON: The Cross-Domain Hack
• JSON and the