SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
JSON
(JavaScript Object Notation)
JSON (JavaScript Object Notation)
 A lightweight data-interchange format

 A subset of the object literal notation of
 JavaScript (or ECMA-262).

 A JSON string must be enclosed by double
 quotes.

 See http://json.org/ for the detailed syntax of
 JSON.
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.
   e.g.: An object with three properties named "a", "b",
   and "c"
   { "a":1,"b":2,"c":3 }

 An ordered list of values.
   In most languages, this is realized as an array, vector,
   list, or sequence.
   e.g.: An array of three integers and one string value
   [ 1, 2, 3, "value #4 with" ]
Using JSON in JavaScript
 Need a JSON parser or a function,
 stringify(), to convert between JavaScript
 objects and JSON encoded data.
   http://www.json.org/json2.js


 JSON encoded data          JavaScript object
   var myObject = eval('(' + myJSONtext + ')');
   var myObject = JSON.parse(myJSONtext);


 JavaScript value       JSON encoded data
   var myJSONText = JSON.stringify(myObject);
Using JSON with XmlHttpRequest
Sending JSON encoded data to the server
  Use HTTP POST method and send the JSON encoded
  data in the body of the request
// xmlhttp is an XmlHttpRequest object
xmlhttp.setRequestHeader(
 'Content-type',
 'application/x-www-form-urlencoded;charset=UTF-8;'
);
xmlhttp.send('jsondata=' + escape(myJSONText));


Handling JSON encoded data from the server
  Server should set the content type to "text/plain"
  In the handler function of xmlhttp object, read
  xmlhttp.responseText
Speeding Up AJAX with JSON
 Both XML and JSON use structured approaches
 to mark up data.

 More and more web services are supporting
 JSON
   e.g.: Yahoo's various search services, travel planners,
   del.icio.us, and highway traffic services
<?xml version='1.0' encoding='UTF-8'?>
<card>
   <fullname>Sean Kelly</fullname>
   <org>SK Consulting</org>
   <emailaddrs>
       <address type='work'>kelly@seankelly.biz</address>
       <address type='home' pref='1'>kelly@seankelly.tv</address>
   </emailaddrs>
   <telephones>
       <tel type='work' pref='1'>+1 214 555 1212</tel>
       <tel type='fax'>+1 214 555 1213</tel>
       <tel type='mobile'>+1 214 555 1214</tel>
   </telephones>
   <addresses>
       <address type='work' format='us'>1234 Main St
          Springfield, TX 78080-1216</address>
       <address type='home' format='us'>5678 Main St
          Springfield, TX 78080-1316</address>
   </addresses>
   <urls>
       <address type='work'>http://seankelly.biz/</address>
       <address type='home'>http://seankelly.tv/</address>
   </urls>
</card>


Example: An address book data encoded in XML
{
    "fullname": "Sean Kelly",
    "org": "SK Consulting",
    "emailaddrs": [
       {"type": "work", "value": "kelly@seankelly.biz"},
       {"type": "home", "pref": 1, "value": "kelly@seankelly.tv"}
    ],
     "telephones": [
       {"type": "work", "pref": 1, "value": "+1 214 555 1212"},
       {"type": "fax", "value": "+1 214 555 1213"},
       {"type": "mobile", "value": "+1 214 555 1214"}
    ],
    "addresses": [
       {"type": "work", "format": "us",
        "value": "1234 Main StnSpringfield, TX 78080-1216"},
       {"type": "home", "format": "us",
        "value": "5678 Main StnSpringfield, TX 78080-1316"}
    ],
     "urls": [
       {"type": "work", "value": "http://seankelly.biz/"},
       {"type": "home", "value": "http://seankelly.tv/"}
    ]
}



Example: The same address book data encoded in JSON
function myHandler() {
   if (req.readyState ==   4 /*complete*/) {
       var addrField   =   document.getElementById('addr');
       var root        =   req.responseXML;
       var addrsElem   =   root.getElementsByTagName('addresses')[0];
       var firstAddr   =   addrsElem.getElementsByTagName('address')[0];
       var addrText    =   fistAddr.firstChild;
       var addrValue   =   addrText.nodeValue;
       addrField.value =   addrValue;
   }
}

JavaScript code to handle XML encoded data
function myHandler() {
   if (req.readyState == 4 /*complete*/) {
       var addrField = document.getElementById('addr');
       var card = eval('(' + req.responseText + ')');
       addrField.value = card.addresses[0].value;
   }
}

JavaScript code to handle JSON encoded data

Both examples try to update the value of a form element
named "addr" with the data obtained from an HTTP request.
XML vs. JSON (in AJAX Application)
 JSON produces slightly smaller documents

 JSON is easier to use in JavaScript

 Parsing JSON encoded data is much faster than
 parsing XML encoded data
XML vs. JSON (in AJAX Application)
 Most web services provide only XML encoded
 data.
   Your server-side script that serves as a proxy to
   external web services can convert XML-encoded data
   to JSON format.

 Using eval() to parse JSON can be dangerous
 if the data are coming from an external source.
   Alternatives – use a JSON parser
     json.org provides a parser written in JavaScript
     Some browsers support native JSON parser
Support for JSON in PHP
 Bundled into PHP 5.2.0+ by default

 JSON functions
   json_decode — Decodes a JSON string
   json_encode — Returns the JSON representation of
   a value
   json_last_error — Returns the last error occured
json_decode()
mixed json_decode ( string $json , bool $assoc)

  Takes a JSON encoded string and converts it
  into a PHP value.

  $json
    The JSON string being decoded

  $assoc
    false (default)   return the value as an object
    true    return the value as an associative array
<?php                            object(stdClass)#1 (3) {
                                     ["a"] => int(1)
$json = '{"a":1,"b":2,"c":3}';       ["b"] => int(2)
var_dump(json_decode($json));        ["c"] => int(3)
var_dump(                        }
   json_decode($json, true)
);                               array(3) {
                                     ["a"] => int(1)
?>                                   ["b"] => int(2)
                                     ["c"] => int(3)
json_decode: Example #1
                                 }
<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>
json_decode: Example #2
<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

?>

json_decode: Example #3
json_encode()
string json_encode ( mixed $value )

  Returns a string containing the JSON
  representation of $value.

  $value
    The value being encoded. Can be any type except a
    resource.
    This function only works with UTF-8 encoded data.
<?php

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
// Output {"a":1,"b":2,"c":3,"d":4,"e":5}

$arr = array ( 1, 2, 3, 4, 5 );
echo json_encode($arr);
// Output [1,2,3,4,5]

$arr['x'] = 10;

echo json_encode($arr);
// Output {"0":1,"1":2,"2":3,"3":4,"4":5,"x":10}

echo json_encode(54321);
// Output 54321

?>

json_encode: Example #1
References
 JSON
   http://json.org/

 PHP Manual: JavaScript Object Notation
   http://www.php.net/json


 Speeding Up AJAX with JSON
   http://www.developer.com/lang/jscript/article.php/359
   6836

Weitere ähnliche Inhalte

Was ist angesagt? (20)

An introduction to json
An introduction to jsonAn introduction to json
An introduction to json
 
Json
JsonJson
Json
 
Json
JsonJson
Json
 
Validating a json in mule
Validating a json in muleValidating a json in mule
Validating a json in mule
 
Intro to JSON
Intro to JSONIntro to JSON
Intro to JSON
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examples
 
Json
JsonJson
Json
 
iOS: Web Services and XML parsing
iOS: Web Services and XML parsingiOS: Web Services and XML parsing
iOS: Web Services and XML parsing
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
Json
JsonJson
Json
 
Json
JsonJson
Json
 
Hands on JSON
Hands on JSONHands on JSON
Hands on JSON
 
Intro to JSON
Intro to JSONIntro to JSON
Intro to JSON
 
An Introduction to JSON JavaScript Object Notation
An Introduction to JSON JavaScript Object NotationAn Introduction to JSON JavaScript Object Notation
An Introduction to JSON JavaScript Object Notation
 
Xml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh malothXml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh maloth
 
Comparing JSON Libraries - July 19 2011
Comparing JSON Libraries - July 19 2011Comparing JSON Libraries - July 19 2011
Comparing JSON Libraries - July 19 2011
 
Mondodb
MondodbMondodb
Mondodb
 
MongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL DatabaseMongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL Database
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
 
MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010
 

Andere mochten auch (6)

JSON
JSONJSON
JSON
 
Json
JsonJson
Json
 
Json short manual
Json short manualJson short manual
Json short manual
 
Json
JsonJson
Json
 
Json
JsonJson
Json
 
Json
JsonJson
Json
 

Ähnlich wie Json

JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptxdyumna2
 
Oracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory DatabaseOracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory DatabaseMarco Gralike
 
Starting with JSON Path Expressions in Oracle 12.1.0.2
Starting with JSON Path Expressions in Oracle 12.1.0.2Starting with JSON Path Expressions in Oracle 12.1.0.2
Starting with JSON Path Expressions in Oracle 12.1.0.2Marco Gralike
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)Faysal Shaarani (MBA)
 
UKOUG Tech14 - Getting Started With JSON in the Database
UKOUG Tech14 - Getting Started With JSON in the DatabaseUKOUG Tech14 - Getting Started With JSON in the Database
UKOUG Tech14 - Getting Started With JSON in the DatabaseMarco Gralike
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)Skillwise Group
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languagesArthur Xavier
 
Zend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryZend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryTricode (part of Dept)
 
Web Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONSWeb Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONSRSolutions
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.jsWebsecurify
 
RESTful JSON web databases
RESTful JSON web databasesRESTful JSON web databases
RESTful JSON web databaseskriszyp
 

Ähnlich wie Json (20)

JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
 
Javascript2839
Javascript2839Javascript2839
Javascript2839
 
Json at work overview and ecosystem-v2.0
Json at work   overview and ecosystem-v2.0Json at work   overview and ecosystem-v2.0
Json at work overview and ecosystem-v2.0
 
Oracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory DatabaseOracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory Database
 
Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
Starting with JSON Path Expressions in Oracle 12.1.0.2
Starting with JSON Path Expressions in Oracle 12.1.0.2Starting with JSON Path Expressions in Oracle 12.1.0.2
Starting with JSON Path Expressions in Oracle 12.1.0.2
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
J s-o-n-120219575328402-3
J s-o-n-120219575328402-3J s-o-n-120219575328402-3
J s-o-n-120219575328402-3
 
Json
JsonJson
Json
 
UKOUG Tech14 - Getting Started With JSON in the Database
UKOUG Tech14 - Getting Started With JSON in the DatabaseUKOUG Tech14 - Getting Started With JSON in the Database
UKOUG Tech14 - Getting Started With JSON in the Database
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languages
 
Zend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryZend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j query
 
Web Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONSWeb Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONS
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
Php sql-android
Php sql-androidPhp sql-android
Php sql-android
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
RESTful JSON web databases
RESTful JSON web databasesRESTful JSON web databases
RESTful JSON web databases
 

Mehr von Raphael Wanjiku

Mehr von Raphael Wanjiku (7)

Road to success
Road to successRoad to success
Road to success
 
Business process and is lecture 2
Business process and is lecture 2Business process and is lecture 2
Business process and is lecture 2
 
Introduction to mis
Introduction to misIntroduction to mis
Introduction to mis
 
Art of css
Art of cssArt of css
Art of css
 
phpClasses and Jquery
phpClasses and JqueryphpClasses and Jquery
phpClasses and Jquery
 
Developing midlets
Developing midletsDeveloping midlets
Developing midlets
 
Introduction to java micro edition
Introduction to java micro editionIntroduction to java micro edition
Introduction to java micro edition
 

Kürzlich hochgeladen

Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataSafe Software
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceMartin Humpolec
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdfJamie (Taka) Wang
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?SANGHEE SHIN
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIUdaiappa Ramachandran
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 

Kürzlich hochgeladen (20)

Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your Salesforce
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AI
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 

Json

  • 2. JSON (JavaScript Object Notation) A lightweight data-interchange format A subset of the object literal notation of JavaScript (or ECMA-262). A JSON string must be enclosed by double quotes. See http://json.org/ for the detailed syntax of JSON.
  • 3. 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. e.g.: An object with three properties named "a", "b", and "c" { "a":1,"b":2,"c":3 } An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. e.g.: An array of three integers and one string value [ 1, 2, 3, "value #4 with" ]
  • 4. Using JSON in JavaScript Need a JSON parser or a function, stringify(), to convert between JavaScript objects and JSON encoded data. http://www.json.org/json2.js JSON encoded data JavaScript object var myObject = eval('(' + myJSONtext + ')'); var myObject = JSON.parse(myJSONtext); JavaScript value JSON encoded data var myJSONText = JSON.stringify(myObject);
  • 5. Using JSON with XmlHttpRequest Sending JSON encoded data to the server Use HTTP POST method and send the JSON encoded data in the body of the request // xmlhttp is an XmlHttpRequest object xmlhttp.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded;charset=UTF-8;' ); xmlhttp.send('jsondata=' + escape(myJSONText)); Handling JSON encoded data from the server Server should set the content type to "text/plain" In the handler function of xmlhttp object, read xmlhttp.responseText
  • 6. Speeding Up AJAX with JSON Both XML and JSON use structured approaches to mark up data. More and more web services are supporting JSON e.g.: Yahoo's various search services, travel planners, del.icio.us, and highway traffic services
  • 7. <?xml version='1.0' encoding='UTF-8'?> <card> <fullname>Sean Kelly</fullname> <org>SK Consulting</org> <emailaddrs> <address type='work'>kelly@seankelly.biz</address> <address type='home' pref='1'>kelly@seankelly.tv</address> </emailaddrs> <telephones> <tel type='work' pref='1'>+1 214 555 1212</tel> <tel type='fax'>+1 214 555 1213</tel> <tel type='mobile'>+1 214 555 1214</tel> </telephones> <addresses> <address type='work' format='us'>1234 Main St Springfield, TX 78080-1216</address> <address type='home' format='us'>5678 Main St Springfield, TX 78080-1316</address> </addresses> <urls> <address type='work'>http://seankelly.biz/</address> <address type='home'>http://seankelly.tv/</address> </urls> </card> Example: An address book data encoded in XML
  • 8. { "fullname": "Sean Kelly", "org": "SK Consulting", "emailaddrs": [ {"type": "work", "value": "kelly@seankelly.biz"}, {"type": "home", "pref": 1, "value": "kelly@seankelly.tv"} ], "telephones": [ {"type": "work", "pref": 1, "value": "+1 214 555 1212"}, {"type": "fax", "value": "+1 214 555 1213"}, {"type": "mobile", "value": "+1 214 555 1214"} ], "addresses": [ {"type": "work", "format": "us", "value": "1234 Main StnSpringfield, TX 78080-1216"}, {"type": "home", "format": "us", "value": "5678 Main StnSpringfield, TX 78080-1316"} ], "urls": [ {"type": "work", "value": "http://seankelly.biz/"}, {"type": "home", "value": "http://seankelly.tv/"} ] } Example: The same address book data encoded in JSON
  • 9. function myHandler() { if (req.readyState == 4 /*complete*/) { var addrField = document.getElementById('addr'); var root = req.responseXML; var addrsElem = root.getElementsByTagName('addresses')[0]; var firstAddr = addrsElem.getElementsByTagName('address')[0]; var addrText = fistAddr.firstChild; var addrValue = addrText.nodeValue; addrField.value = addrValue; } } JavaScript code to handle XML encoded data function myHandler() { if (req.readyState == 4 /*complete*/) { var addrField = document.getElementById('addr'); var card = eval('(' + req.responseText + ')'); addrField.value = card.addresses[0].value; } } JavaScript code to handle JSON encoded data Both examples try to update the value of a form element named "addr" with the data obtained from an HTTP request.
  • 10. XML vs. JSON (in AJAX Application) JSON produces slightly smaller documents JSON is easier to use in JavaScript Parsing JSON encoded data is much faster than parsing XML encoded data
  • 11. XML vs. JSON (in AJAX Application) Most web services provide only XML encoded data. Your server-side script that serves as a proxy to external web services can convert XML-encoded data to JSON format. Using eval() to parse JSON can be dangerous if the data are coming from an external source. Alternatives – use a JSON parser json.org provides a parser written in JavaScript Some browsers support native JSON parser
  • 12. Support for JSON in PHP Bundled into PHP 5.2.0+ by default JSON functions json_decode — Decodes a JSON string json_encode — Returns the JSON representation of a value json_last_error — Returns the last error occured
  • 13. json_decode() mixed json_decode ( string $json , bool $assoc) Takes a JSON encoded string and converts it into a PHP value. $json The JSON string being decoded $assoc false (default) return the value as an object true return the value as an associative array
  • 14. <?php object(stdClass)#1 (3) { ["a"] => int(1) $json = '{"a":1,"b":2,"c":3}'; ["b"] => int(2) var_dump(json_decode($json)); ["c"] => int(3) var_dump( } json_decode($json, true) ); array(3) { ["a"] => int(1) ?> ["b"] => int(2) ["c"] => int(3) json_decode: Example #1 } <?php $json = '{"foo-bar": 12345}'; $obj = json_decode($json); print $obj->{'foo-bar'}; // 12345 ?> json_decode: Example #2
  • 15. <?php // the following strings are valid JavaScript but not valid JSON // the name and value must be enclosed in double quotes // single quotes are not valid $bad_json = "{ 'bar': 'baz' }"; json_decode($bad_json); // null // the name must be enclosed in double quotes $bad_json = '{ bar: "baz" }'; json_decode($bad_json); // null // trailing commas are not allowed $bad_json = '{ bar: "baz", }'; json_decode($bad_json); // null ?> json_decode: Example #3
  • 16. json_encode() string json_encode ( mixed $value ) Returns a string containing the JSON representation of $value. $value The value being encoded. Can be any type except a resource. This function only works with UTF-8 encoded data.
  • 17. <?php $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); // Output {"a":1,"b":2,"c":3,"d":4,"e":5} $arr = array ( 1, 2, 3, 4, 5 ); echo json_encode($arr); // Output [1,2,3,4,5] $arr['x'] = 10; echo json_encode($arr); // Output {"0":1,"1":2,"2":3,"3":4,"4":5,"x":10} echo json_encode(54321); // Output 54321 ?> json_encode: Example #1
  • 18. References JSON http://json.org/ PHP Manual: JavaScript Object Notation http://www.php.net/json Speeding Up AJAX with JSON http://www.developer.com/lang/jscript/article.php/359 6836