|
1、JSON數(shù)據(jù)格式介紹
2、對(duì)數(shù)據(jù)編碼成JSON格式
3、對(duì)JSON數(shù)據(jù)進(jìn)行解碼,并操作
JSON數(shù)據(jù)格式表示方式如下:
復(fù)制代碼 代碼如下:
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] }
用php將數(shù)據(jù)編碼成JSON格式:
復(fù)制代碼 代碼如下:
<?php
//php中用數(shù)組表示JSON格式數(shù)據(jù)
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非誠(chéng)'),
'lastname' => iconv('gb2312', 'utf-8', '勿擾'),
'contact' => array(
'email' =>'fcwr@jb51.NET',
'website' =>'http://www.jb51.NET',
)
);
//將數(shù)組編碼成JSON數(shù)據(jù)格式
$json_string = json_encode($arr);
//JSON格式數(shù)據(jù)可直接輸出
echo $json_string;
?>
需要指出的是,在非UTF-8編碼下,中文字符將不可被encode,結(jié)果會(huì)出來(lái)空值,所以,如果你使用 gb2312編寫php代碼,那么就需要將包含中文的內(nèi)容使用iconv或者mb轉(zhuǎn)為UTF-8再進(jìn)行json_encode。
輸出:(JSON格式)
{"firstname":"/u975e/u8bda","lastname":"/u52ff/u6270","contact":{"email":"fcwr@jb51.NET","website":"http:////www.jb51.NET"}}
用php對(duì)JSON數(shù)據(jù)進(jìn)行解碼并處理:
復(fù)制代碼 代碼如下:
<?php
//php中用數(shù)組表示JSON格式數(shù)據(jù)
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非誠(chéng)'),
'lastname' => iconv('gb2312', 'utf-8', '勿擾'),
'contact' => array(
'email' =>'fcwr@jb51.NET',
'website' =>'http://www.jb51.NET',
)
);
//將數(shù)組編碼成JSON數(shù)據(jù)格式
$json_string = json_encode($arr);
//將JSON格式數(shù)據(jù)進(jìn)行解碼,解碼后不是JSON數(shù)據(jù)格式,不可用echo直接輸出
$obj = json_decode($json_string);
//強(qiáng)制轉(zhuǎn)化為數(shù)組格式
$arr = (array) $obj;
//按數(shù)組方式調(diào)用里面的數(shù)據(jù)
echo iconv('utf-8','gb2312',$arr['firstname']);
echo '</br>';
//輸出數(shù)組結(jié)構(gòu)
print_r($arr);
?>
輸出:
非誠(chéng)
Array ( [firstname] => 主站蜘蛛池模板: 醴陵市| 丁青县| 陈巴尔虎旗| 麟游县| 都安| 宁化县| 弥勒县| 延长县| 无极县| 漳平市| 芜湖市| 岳普湖县| 武邑县| 贡山| 云龙县| 安溪县| 武山县| 荥经县| 双鸭山市| 孙吴县| 五华县| 乳源| 穆棱市| 谢通门县| 扶余县| 成武县| 玉田县| 邹城市| 夏河县| 大丰市| 朝阳市| 万盛区| 南陵县| 庐江县| 罗山县| 肃宁县| 独山县| 民和| 平阳县| 资中县| 潼南县|