php中的json_encode()和json_decode()函數的一些說明

來源:互聯網
上載者:User

標籤:cti   input   字串   replace   方法   style   索引   不能   輸出   

1,php定義對象字面量時,不支援直接書寫,如{“a":"11","b":"22"}。這種書寫方式在其他語言中被支援,在php中需要按如下方式定義:

  ①  $a = ‘{“a":"11","b":"22"}‘【這是json字串,不加外面的引號則是json對象】

  ②  $b = json_decode($a); 

  這樣$b就是對象字面量了。

2,關於json_encode($value)的機制詳解

  ①  $value為字串 “aa"時,調用此函數後輸出字串 "aa";

  ②  $value為索引數組時,如["aa","bb"],調用此函數後輸出數組 ["aa","bb"] 的字串形式;

  ③  $value為關聯陣列時,如["aa"=>"11","bb"=>"22"],調用此函數後輸出對象 {"aa":11,"bb":22} 的字串形式;

  json_decode($json)的機制和json_encode($value)相同,反過來即可。注意,當為字串時,只有這種形式能被解析 json_decode(‘ "bb" ‘)

  即單引號在最外面,裡麵包含雙引號和字元。其他形式 “bb" 或 ‘bb‘ 或 " ‘bb‘ "都不能被json_decode()函數解析。

3,改進後的json_encode()和json_decode()函數,支援漢語(原生的不支援漢語)

  註:php中不可直接改寫原生函數,需要寫在類裡,作為類的一個方法

static function json_encode($input)
{
// 從 PHP 5.4.0 起, 增加了這個選項.
if (defined(‘JSON_UNESCAPED_UNICODE‘)) {
return json_encode($input, JSON_UNESCAPED_UNICODE);
}

if (is_string($input)) {
$text = $input;
$text = str_replace(‘\\‘, ‘\\\\‘, $text);
$text = str_replace(
array("\r", "\n", "\t", "\""),
array(‘\r‘, ‘\n‘, ‘\t‘, ‘\\"‘),
$text);
return ‘"‘ . $text . ‘"‘;
} else if (is_array($input) || is_object($input)) {
$arr = array();
$is_obj = is_object($input) || (array_keys($input) !== range(0, count($input) - 1));
foreach ($input as $k => $v) {
if($v == null){
$v = ‘null‘;
}
if ($is_obj) {
$arr[] = self::json_encode($k) . ‘:‘ . self::json_encode($v);
} else {
$arr[] = self::json_encode($v);
}
}

if ($is_obj) {
return ‘{‘ . join(‘,‘, $arr) . ‘}‘;
} else {
return ‘[‘ . join(‘,‘, $arr) . ‘]‘;
}
} else {
return $input . ‘‘;
}
}

php中的json_encode()和json_decode()函數的一些說明

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.