About The Tutorial - Dipartimento Di Informatica

Transcription

About the TutorialJSON or JavaScript Object Notation is a lightweight text-based open standard designedfor human-readable data interchange. The JSON format was originally specified byDouglas Crockford, and is described in RFC 4627. The official Internet media type forJSON is application/json. The JSON filename extension is .json.This tutorial will help you understand JSON and its use within various programminglanguages such as PHP, PERL, Python, Ruby, Java, etc.AudienceThis tutorial has been designed to help beginners understand the basic functionality ofJavaScript Object Notation (JSON) to develop the data interchange format. Aftercompleting this tutorial, you will have a good understanding of JSON and how to use itwith JavaScript, Ajax, Perl, etc.PrerequisitesBefore proceeding with this tutorial, you should have a basic understanding of the webapplication’s work over HTTP and we assume that you have a basic knowledge ofJavaScript.Copyright & Disclaimer Copyright 2017 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point(I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute orrepublish any contents or a part of contents of this e-book in any manner without writtenconsent of the publisher.We strive to update the contents of our website and tutorials as timely and as preciselyas possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I)Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness ofour website or its contents including this tutorial. If you discover any errors on ourwebsite or in this tutorial, please notify us at contact@tutorialspoint.comi

Table of ContentsAbout the Tutorial . iAudience . iPrerequisites . iCopyright & Disclaimer. iTable of Contents . ii1.JSON OVERVIEW . 1Uses of JSON . 1Characteristics of JSON . 1Simple Example in JSON . 12.JSON SYNTAX . 43.JSON DATATYPES . 5Number . 5String . 6Boolean . 7Array . 7Object . 8Whitespace . 8null . 9JSON Value . 94.JSON OBJECTS. 10Creating Simple Objects . 10Creating Array Objects . 11ii

5.JSON SCHEMA . 13JSON Schema Validation Libraries . 13JSON Schema Example . 146.JSON COMPARISON WITH XML. 177.JSON JSON WITH PHP . 18Environment . 18JSON Functions. 18Encoding JSON in PHP (json encode) . 18Decoding JSON in PHP (json decode) . 198.JSON JSON WITH PERL . 21Environment . 21JSON Functions. 21Encoding JSON in Perl (encode json) . 22Decoding JSON in Perl (decode json) . 239.JSON JSON WITH PYTHON . 25Environment . 25JSON Functions. 25Encoding JSON in Python (encode) . 25Decoding JSON in Python (decode) . 2610. JSON JSON WITH RUBY . 27Environment . 27Parsing JSON using Ruby . 27iii

11. JSON JSON WITH JAVA . 29Environment . 29Mapping between JSON and Java entities . 29Encoding JSON in Java . 30Decoding JSON in Java . 3112. JSON JSON WITH AJAX . 33iv

1. JSON OverviewJSONJSON or JavaScript Object Notation is a lightweight text-based open standard designedfor human-readable data interchange. Conventions used by JSON are known toprogrammers, which include C, C , Java, Python, Perl, etc. JSON stands for JavaScript Object Notation. The format was specified by Douglas Crockford. It was designed for human-readable data interchange. It has been extended from the JavaScript scripting language. The filename extension is .json. JSON Internet Media type is application/json. The Uniform Type Identifier is public.json.Uses of JSON It is used while writing JavaScript based applications that includes browserextensions and websites. JSON format is used for serializing and transmitting structured data over networkconnection. It is primarily used to transmit data between a server and web applications. Web services and APIs use JSON format to provide public data. It can be used with modern programming languages.Characteristics of JSON JSON is easy to read and write. It is a lightweight text-based interchange format. JSON is language independent.Simple Example in JSONThe following example shows how to use JSON to store information related to booksbased on their topic and edition.{"book": [{1

JSON"id":"01","language": "Java","edition": "third","author": "Herbert Schildt"},{"id":"07","language": "C ","edition": "second""author": "E.Balagurusamy"}]}After understanding the above program, we will try another example. Let's save thebelow code as json.htm: html head title JSON example /title script language "javascript" var object1 { "language" : "Java", "author": "herbert schildt" };document.write(" h1 JSON with JavaScript example /h1 ");document.write(" br ");document.write(" h3 Language " object1.language " /h3 ");document.write(" h3 Author " object1.author " /h3 ");var object2 { "language" : "C ", "author": "E-Balagurusamy" };document.write(" br ");document.write(" h3 Language " object2.language " /h3 ");document.write(" h3 Author " object2.author " /h3 ");document.write(" hr / ");document.write(object2.language " programming language can be studied " "from book written by " object2.author);document.write(" hr / ");2

JSON /script /head body /body /html Now let's try to open json.htm using IE or any other javascript enabled browser thatproduces the following result:You can refer to JSON Objects chapter for more information on JSON objects.3

2. JSON SyntaxJSONLet's have a quick look at the basic syntax of JSON. JSON syntax is basically consideredas a subset of JavaScript syntax; it includes the following: Data is represented in name/value pairs. Curly braces hold objects and each name is followed by ':'(colon), thename/value pairs are separated by , (comma). Square brackets hold arrays and values are separated by ,(comma).Below is a simple example:{"book": [{"id":"01","language": "Java","edition": "third","author": "Herbert Schildt"},{"id":"07","language": "C ","edition": "second""author": "E.Balagurusamy"}]}JSON supports the following two data structures: Collection of name/value pairs: This Data Structure is supported by differentprogramming languages. Ordered list of values: It includes array, list, vector or sequence etc.4

3. JSON DataTypesJSONJSON format supports the following data types:TypeDescriptionNumberdouble- precision floating-point format in JavaScriptStringdouble-quoted Unicode with backslash escapingBooleantrue or falseArrayan ordered sequence of valuesValueit can be a string, a number, true or false, null etcObjectan unordered collection of key:value pairsWhitespacecan be used between any pair of tokensnullemptyNumber It is a double precision floating-point format in JavaScript and it depends onimplementation. Octal and hexadecimal formats are not used. No NaN or Infinity is used in Number.The following table shows the number types:TypeDescriptionIntegerDigits 1-9, 0 and positive or negativeFractionFractions like .3, .9ExponentExponent like e, e , e-,E, E , E5

JSONSyntaxvar json-object-name {"string" : number value, .}ExampleExample showing Number Datatype, value should not be quoted:var obj {"marks": 97}String It is a sequence of zero or more double quoted Unicode characters with backslashescaping. Character is a single character string i.e. a string with length 1.The table shows various special characters that you can use in strings of a JSONdocument:TypeDescription"double quotation\backslash/forward slashbbackspacefform feednnew linercarriage returnthorizontal tabufour hexadecimal digitsSyntaxvar json-object-name { string : "string value", .}6

JSONExampleExample showing String Datatype:var obj {"name": "Amit"}BooleanIt includes true or false values.Syntaxvar json-object-name { string : true/false, .}Examplevar obj {"name": "Amit", "marks": 97, "distinction": true}Array It is an ordered collection of values. These are enclosed in square brackets which means that array begins with .[. andends with .]. The values are separated by , (comma). Array indexing can be started at 0 or 1. Arrays should be used when the key names are sequential integers.Syntax[ value, .]ExampleExample showing array containing multiple objects:{"books": [{ "language":"Java" , "edition":"second" },{ "language":"C " , "lastName":"fifth" },{ "language":"C" , "lastName":"third" }]}7

JSONObject It is an unordered set of name/value pairs. Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'. Each name is followed by ':'(colon) and the key/value pairs are separated by ,(comma). The keys must be strings and should be different from each other. Objects should be used when the key names are arbitrary strings.Syntax{ string : value, .}ExampleExample showing Object:{"id": "011A","language": "JAVA","price": 500,}WhitespaceIt can be inserted between any pair of tokens. It can be added to make a code morereadable. Example shows declaration with and without whitespace:Syntax{string: "",.}Examplevar obj1 {"name": "Sachin Tendulkar"}var obj2 {"name": "SauravGanguly"}8

JSONnullIt means empty type.SyntaxnullExamplevar i null;if(i 1){document.write(" h1 value is 1 /h1 ");}else{document.write(" h1 value is null /h1 ");}JSON ValueIt includes: number (integer or floating point) string boolean array object nullSyntaxString Number Object Array TRUE FALSE NULLExamplevar i 1;var j "sachin";var k null;9

JSON4. JSON ObjectsCreating Simple ObjectsJSON objects can be created with JavaScript. Let us see the various ways of creatingJSON objects using JavaScript: Creation of an empty Object:var JSONObj {}; Creation of a new Object:var JSONObj new Object(); Creation of an object with attribute bookname with value in string,attribute price with numeric value. Attribute is accessed by using '.' Operator:var JSONObj { "bookname ":"VB BLACK BOOK", "price":500 };This is an example that shows creation of an object in javascript using JSON, save thebelow code as json object.htm: html head title Creating Object JSON with JavaScript /title script language "javascript" var JSONObj { "name" : "tutorialspoint.com", "year": 2005 };document.write(" h1 JSON with JavaScript example /h1 ");document.write(" br ");document.write(" h3 Website Name " JSONObj.name " /h3 ");document.write(" h3 Year " JSONObj.year " /h3 "); /script /head body /body /html 10

JSONNow let's try to open json object.htm using IE or any other javascript enabled browser.It produces the following result:Creating Array ObjectsThe following example shows creation of an array object in javascript using JSON, savethe below code as json array object.htm: html head title Creation of array object in javascript using JSON /title script language "javascript" document.writeln(" h2 JSON array object /h2 ");var books { "Pascal" : [{ "Name": "Pascal Made Simple", "price" : 700 },{ "Name": "Guide to Pascal", "price" : 400 }],"Scala": [{ "Name": "Scala for the Impatient", "price" : 1000 },{ "Name": "Scala in Depth", "price" : 1300 }]}var i 0document.writeln(" table border '2' tr ");for(i 0;i books.Pascal.length;i ){document.writeln(" td ");11

JSONdocument.writeln(" table border '1' width 100 ");document.writeln(" tr td b Name /b /td td width 50 " books.Pascal[i].Name " /td /tr ");document.writeln(" tr td b Price /b /td td width 50 " books.Pascal[i].price " /td /tr ");document.writeln(" /table ");document.writeln(" /td ");}for(i 0;i books.Scala.length;i ){document.writeln(" td ");document.writeln(" table border '1' width 100 ");document.writeln(" tr td b Name /b /td td width 50 " books.Scala[i].Name " /td /tr ");document.writeln(" tr td b Price /b /td td width 50 " books.Scala[i].price " /td /tr ");document.writeln(" /table ");document.writeln(" /td ");}document.writeln(" /tr /table "); /script /head body /body /html Now let's try to open json array object.htm using IE or any other javascript enabledbrowser. It produces the following result:12

5. JSON SchemaJSONJSON Schema is a specification for JSON based format for defining the structure of JSONdata. It was written under IETF draft which expired in 2011. JSON Schema: Describes your existing data format. Clear, human- and machine-readable documentation. Complete structural validation, useful for automated testing. Complete structural validation, validating client-submitted data.JSON Schema Validation LibrariesThere are several validators currently available for different programming languages.Currently the most complete and compliant JSON Schema validator available is JSV.LanguagesLibrariesCWJElement (LGPLv3)Javajson-schema-validator (LGPLv3).NETJson.NET (MIT)ActionScript 3Frigga (MIT)Haskellaeson-schema (MIT)PythonJsonschemaRubyautoparse (ASL 2.0); ruby-jsonschema (MIT)PHPphp-json-schema (MIT). json-schema (Berkeley)JavaScriptOrderly (BSD); JSV; json-schema; Matic (MIT); Dojo; Persevere(modified BSD or AFL 2.0); schema.js.13

JSONJSON Schema ExampleGiven below is a basic JSON schema, which covers a classical product catalogdescription:{" schema": "http://json-schema.org/draft-04/schema#","title": "Product","description": "A product from Acme's catalog","type": "object","properties": {"id": {"description": "The unique identifier for a product","type": "integer"},"name": {"description": "Name of the product","type": "string"},"price": {"type": "number","minimum": 0,"exclusiveMinimum": true}},"required": ["id", "name", "price"]}Let's check the various important keywords that can be used in this schema:KeywordsDescription schemaThe schema keyword states that this schema is writtenaccording to the draft v4 specification.titleYou will use this to give a title to your schema.descriptionA little description of the schema.14

JSONtypeThe type keyword defines the first constraint on our JSON data: ithas to be a JSON Object.propertiesDefines various keys and their value types, minimum andmaximum values to be used in JSON file.requiredThis keeps a list of required properties.minimumThis is the constraint to be put on the value and representsminimum acceptable value.exclusiveMinimumIf "exclusiveMinimum" is present and has boolean value true, theinstance is valid if it is strictly greater than the value of"minimum".maximumThis is the constraint to be put on the value and representsmaximum acceptable value.exclusiveMaximumIf "exclusiveMaximum" is present and has boolean value true, theinstance is valid if it is strictly lower than the value of"maximum".multipleOfA numeric instance is valid against "multipleOf" if the result of thedivision of the instance by this keyword's value is an integer.maxLengthThe length of a string instance is defined as the maximumnumber of its characters.minLengthThe length of a string instance is defined as the minimum numberof its characters.patternA string instance is considered valid if the regular expressionmatches the instance successfully.15

JSONYou can check a http://json-schema.org for the complete list of keywords that can beused in defining a JSON schema. The above schema can be used to test the validity ofthe following JSON code:[{"id": 2,"name": "An ice sculpture","price": 12.50,},{"id": 3,"name": "A blue mouse","price": 25.50,}]16

6. JSON Comparison with XMLJSONJSON and XML are human readable formats and are language independent. They bothhave support for creation, reading and decoding in real world situations. We cancompare JSON with XML, based on the following factors:VerboseXML is more verbose than JSON, so it is faster to write JSON for programmers.Arrays UsageXML is used to describe the structured data, which doesn't include arrays whereas JSONinclude arrays.ParsingJavaScript's eval method parses JSON. When applied to JSON, eval returns the describedobject.ExampleIndividual examples of XML and JSON:JSON{"company": Volkswagen,"name": "Vento","price": 800000}XML car company Volkswagen /company name Vento /name price 800000 /price /car 17

7. JSON JSON with PHPJSONThis chapter covers how to encode and decode JSON objects using PHP programminglanguage. Let's start with preparing the environment to start our programming with PHPfor JSON.EnvironmentAs of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.JSON FunctionsFunctionLibrariesjson encodeReturns the JSON representation of a value.json decodeDecodes a JSON string.json last errorReturns the last error occurred.Encoding JSON in PHP (json encode)PHP json encode() function is used for encoding JSON in PHP. This function returns theJSON representation of a value on success or FALSE on failure.Syntaxstring json encode ( value [, options 0 ] )Parameters value: The value being encoded. This function only works with UTF-8 encodeddata. options: This optional value is a bitmask consisting of JSON HEX QUOT,JSON HEX TAG, JSON HEX AMP, JSON HEX APOS,JSON NUMERIC CHECK,JSON PRETTY PRINT, JSON UNESCAPED SLASHES,JSON FORCE OBJECT.18

JSONExampleThe following example shows how to convert an array into JSON with PHP: ?php arr array('a' 1, 'b' 2, 'c' 3, 'd' 4, 'e' 5);echo json encode( arr);? While executing, this will produce the following result:{"a":1,"b":2,"c":3,"d":4,"e":5}The following example shows how the PHP objects can be converted into JSON: ?phpclass Emp {public name "";public hobbies "";public birthdate "";} e new Emp(); e- name "sachin"; e- hobbies "sports"; e- birthdate date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p"); e- birthdate date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));echo json encode( e);? While executing, this will produce the following ate":"08\/05\/1974 12:20:03 pm"}Decoding JSON in PHP (json decode)PHP json decode() function is used for decoding JSON in PHP. This function returns thevalue decoded from json to appropriate PHP type.Syntaxmixed json decode ( json [, assoc false [, depth 512 [, options 0 ]]])19

JSONParamaters json string: It is an encoded string which must be UTF-8 encoded data. assoc: It is a boolean type parameter, when set to TRUE, returned objects will beconverted into associative arrays. depth: It is an integer type parameter which specifies recursion depth options:ItisanintegertypeJSON BIGINT AS STRING is supported.bitmaskofJSONdecode,ExampleThe following example shows how PHP can be used to decode JSON objects: ?php json '{"a":1,"b":2,"c":3,"d":4,"e":5}';var dump(json decode( json));var dump(json decode( json, true));? While executing, it will produce the following result:object(stdClass)#1 (5) {["a"] int(1)["b"] int(2)["c"] int(3)["d"] int(4)["e"] int(5)}array(5) {["a"] int(1)["b"] int(2)["c"] int(3)["d"] int(4)["e"] int(5)}20

8. JSON JSON with PerlJSONThis chapter covers how to encode and decode JSON objects using Perl programminglanguage. Let's start with preparing the environment to start our programming with Perlfor JSON.EnvironmentBefore you start encoding and decoding JSON using Perl, you need to install JSONmodule, which can be obtained from CPAN. Once you downloaded JSON-2.53.tar.gz orany other latest version, follow the steps mentioned below: tar xvfz JSON-2.53.tar.gz cd JSON-2.53 perl Makefile.PL make make installJSON FunctionsFunctionLibrariesencode jsonConverts the given Perl data structure to a UTF-8 encoded, binarystring.decode jsonDecodes a JSON string.to jsonConverts the given Perl data structure to a json string.from jsonExpects a json string and tries to parse it, returning the resultingreference.convert blessedUse this function with true value so that Perl can use TO JSONmethod on the object's class to convert an object into JSON.21

JSONEncoding JSON in Perl (encode json)Perl encode json() function converts the given Perl data structure to a UTF-8 encoded,binary string.Syntax: json text encode json ( perl scalar );or json text JSON- new- utf8- encode( perl scalar);ExampleThe following example shows arrays under JSON with Perl:#!/usr/bin/perluse JSON;my %rec hash ('a' 1, 'b' 2, 'c' 3, 'd' 4, 'e' 5);my json encode json \%rec hash;print " json\n";While executing, this will produce the following result:{"e":5,"c":3,"a":1,"b":2,"d":4}The following example shows how Perl objects can be converted into JSON:#!/usr/bin/perlpackage Emp;sub new{my class shift;my self {name shift,hobbiesbirthdate shift, shift,};bless self, class;22

JSONreturn self;}sub TO JSON { return { %{ shift() } }; }package main;use JSON;my JSON JSON- new- utf8; JSON- convert blessed(1); e new Emp( "sachin", "sports", "8/5/1974 12:20:03 pm"); json JSON- encode( e);print " json\n";On executing, it will produce the following result:{"birthdate":"8/5/1974 12:20:03 pm","name":"sachin","hobbies":"sports"}Decoding JSON in Perl (decode json)Perl decode json() function is used for decoding JSON in Perl. This function returns thevalue decoded from json to an appropriate Perl type.Syntax: perl scalar decode json json textor perl scalar JSON- new- utf8- decode( json text)ExampleThe following example shows how Perl can be used to decode JSON objects. Here youwill need to install Data::Dumper module if you already do not have it on your machine.#!/usr/bin/perluse JSON;use Data::Dumper; json '{"a":1,"b":2,"c":3,"d":4,"e":5}';23

JSON text decode json( json);printDumper( text);On executing, it will produce following result: VAR1 {'e' 5,'c' 3,'a' 1,'b' 2,'d' 4};24

9. JSON JSON with PythonJSONThis chapter covers how to encode and decode JSON objects using Python programminglanguage. Let's start with preparing the environment to start our programming withPython for JSON.EnvironmentBefore you start with encoding and decoding JSON using Python, you need to install anyof the JSON modules available. For this tutorial we have downloaded and installedDemjson (http://deron.meranda.us/python/demjson/) as follows: tar xvfz demjson-1.6.tar.gz cd demjson-1.6 python setup.py installJSON FunctionsFunctionLibrariesencodeEncodes the Python object into a JSON string representation.decodeDecodes a JSON-endoded string into a Python object.Encoding JSON in Python (encode)Python encode() function encodes the Python object into a JSON string representation.Syntaxdemjson.encode(self, obj, nest level 0)ExampleThe following example shows arrays under JSON with Python.#!/usr/bin/pythonimport demjsondata [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]25

JSONjson demjson.encode(data)print jsonWhile executing, this will produce the following result:[{"a":1,"b":2,"c":3,"d":4,"e":5}]Decoding JSON in Python (decode)Python can use demjson.decode() function for decoding JSON. This function returns thevalue decoded from json to an appropriate Python type.Syntaxdemjson.decode(self, txt)ExampleThe following example shows how Python can be used to decode JSON objects.#!/usr/bin/pythonimport demjsonjson '{"a":1,"b":2,"c":3,"d":4,"e":5}';text demjson.decode(json)printtextOn executing, it will produce the following result:{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}26

10.JSON JSON with RubyJSONThis chapter covers how to encode and decode JSON objects using Ruby programminglanguage. Let's start with preparing the environment to start our programming withRuby for JSON.EnvironmentBefore you start with encoding and decoding JSON using Ruby, you need to install any ofthe JSON modules available for Ruby. You may need to install Ruby gem, but if you arerunning latest version of Ruby then you must have gem already installed on yourmachine, otherwise let's follow the following single step assuming you already have geminstalled: gem install jsonParsing JSON using RubyThe following example shows that the first 2 keys hold string values and the last 3 keyshold arrays of strings. Let's keep the following content in

It has been extended from the JavaScript scripting language. The filename extension is.json. JSON Internet Media type is application/json. The Uniform Type Identifier is public.json. Uses of JSON It is used while writing JavaScript based applications that includes browser extensions and websites.