1. 程式人生 > >JavaScript -- JSON.parse 函式 和 JSON.stringify 函式

JavaScript -- JSON.parse 函式 和 JSON.stringify 函式

JavaScript -- JSON.parse 函式 和 JSON.stringify 函式

1. JSON.parse 函式: 使用 JSON.parse 可將 JSON 字串轉換成物件。

<!doctype html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script type="text/javascript">
        var jsontext = '{"Name":"xiaohuzi","Age":"26","Email":"
[email protected]
","Phone":"123456789"}
'; var p = JSON.parse(jsontext); alert(p.Name + ", " + p.Age+", "+p.Email+", "+p.Phone); </script> </head> <body>

 執行結果:

 

2. JSON.stringify 函式:  可將 JavaScript 物件轉換為Json表示字串。

<!doctype html>
<html>
 <head>
  <meta charset="
UTF-8"> <title>Document</title> <script type="text/javascript"> var Person = new Object(); Person.Name = "XiaoHuzi"; Person.Age = 26; Person.Email="[email protected]"; var jsonText = JSON.stringify(Person); alert(jsonText);
</script> </head> <body>

執行結果: