Json ( javascript object notation)
description
Transcript of Json ( javascript object notation)
420-B63 Programmation Web AvancéeAuteur : Frédéric Thériault
1
À quoi ça sert !?
2
Format d’échange entre différentes technologies. Sérialise les objets/tableaux/… en texte JSON en
utilisant des symboles : [], :, {}, … C’est une très bonne technique à utiliser pour le
développement AJAX PHP supporte JSON depuis 5.2. Site Web : http://www.json.org/ Il est fortement conseillé de travailler en UTF-8
avec JSON (pour le transport des accents).
Exemple de texte JSON
Le texte JSON suit le format standard de JavaScript :
<script type="text/javascript">
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
var jsonTexte = JSON.stringify(mycars);
alert(jsonTexte);
</script>
Ceci affichera : ["Saab","Volvo","BMW"] (c’est le texte JSON)
3
Pour l’utiliser… JavaScript :
Avoir intégré la librairie JSON à sa page Web, sauf dans certains navigateurs qui le supportent déjà.○ Var objTmp = JSON.stringify(texte)
Transforme en texte JSON
○ Var obj = JSON.parse(objTmp)
Transforme un texte JSON en entité JavaScript
4
Pour l’utiliser… (suite) PHP
En considérant un tableau comme suit :
$maVariable = array();
$maVariable[] = array('John', 'Smith', 'Concierge');
$maVariable[] = array('Roger', 'Eddie', 'Joueur de hockey');
…
On appelle la fonction json_encode($maVariable) pour transformer le tableau en texte JSON
echo json_encode($maVariable);
La fonction json_decode($variable) permet de construire un texte JSON en entité PHP.
5