---
title: "JavaScript对象与JSON字符串的相互转换"
author: "luowei31"
date: "2012-02-27T15:41:06Z"
tags: []
categories: ["Web前端"]
slug: "javascript-json"
draft: false
lastmod: "2012-02-27T15:41:06Z"
id: 1426514
url: "https://luowei31.iteye.com/blog/1426514"
---

[JSON（JavaScript Object Notation）](http://www.olnote.com/itlife/note/100000096.html "JSON 简介") 是JavaScript编程语言的一个子集。正因JSON是JavaScript的一个子集，所以它可清晰的运用于此语言中。

eval函数 JSON文本转换为对象

    为了将JSON文本转换为对象，可以使用eval函数。eval函数调用JavaScript编辑器。由于JSON是JavaScript的子集，因此编译器将正确的解析文本并产生对象结构。文本必须括在括号中避免产生JavaScript的语法歧义。  
var obj = eval('(' + JSONTest + ')');  
    eval函数非常快速。它可以编译执行任何JavaScript程序，因此产生了安全性问题。当使用可信任与完善的源代码时才可以使用eval函数。这样可以更安全的解析JSON文本。使用XmlHttp的web应用，页面之间的通讯只允许同源，因此是可以信任的。但这却不是完善的。如果服务器没有严谨的JSON编码，或者没有严格的输入验证，那么可能传送包括危险脚本的无效JSON文本。eval函数将执行恶意的脚本。

JSON解释器 JSON.parse、JSON.stringify

    使用JSON解析器可以防止像eval函数转换JSON文本为对象那样的安全隐患。JSON解析器只能辨识JSON文本，拒绝所有脚本。提供了本地JSON支持的浏览器的JSON解析器将远快于eval函数。  
目前，Firefox、Opera、IE8以上版本也提供了本地JSON支持。其中，JSON解释器提供的函数有：JSON.parse、JSON.stringify。  
    对于那些并不提供本地JSON支持的浏览器可以引入脚本json2.js，来实现JSON转换功能。json2.js脚本可到[https://github.com/douglascrockford/JSON-js/blob/master/json2.js](https://github.com/douglascrockford/JSON-js/blob/master/json2.js "json2.js 下载页面")页面下载。

JSON.parse 函数

将JSON文本转换为对象。  
JSON.parse(text\[, reviver])

参数

text  
   必选项。要转换为对象的JSON文本。  
reviver  
   可选项。该参数是个替换函数。在转换中，遍历的每个节点，都将执行该函数，该函数的返回值将替代转换结果的相应节点值。

JSON.stringify 函数

将对象转换为JSON文本。  
JSON.stringify(value\[, replacer\[, space]])

参数

text  
必选项。要转换为JSON文本的对象。  
reviver  
   可选项。该参数是个替换函数。在转换中，遍历的每个节点，都将执行该函数，该函数的返回值将替代转换结果的相应节点值。  
space  
   可选项。格式化输出JSON文本缩进的空格数量。如果不提供该参数将不会格式化输出。

参数reviver的委托类型

reviver(key, value)  
reviver函数的中的this是当前所遍历到的节点的父节点。当所遍历的是根节点的时候，父节点是个Object对象，根节点是该对象的一个属性，属性名是空字符串。

参数

key  
   当父节点是数组Object，key为数组索引，否则key为Object属性名。  
value  
   节点值。

注：JSON不支持循环数据结构。

JSON.parse、JSON.stringify使用示例

&lt;script type="text/javascript"&gt;  
function InventoryItem(parm) {  
   this.Product = parm.Product  
   this.Quantity = parm.Quantity;  
   this.Price = parm.Price;  
   this.Type = parm.Type;  
   this.Total = function() {  
      return this.Price * this.Quantity;  
   }  
}

function Inventory(parm) {  
   this.Date = parm.Date;  
   this.Item = parm.Item;  
   this.Type = parm.Type;  
   this.Total = function() {  
      var count = 0;  
      for (var key in this.Item) {  
         count += this.Item\[key].Total();  
      }  
      return count;  
   }  
}

var inventoryJSONText = "{\\"Date\\":\\"2000-01-01\\",\\"Item\\":\[{\\"Product\\":\\"ProductOne\\",\\"Quantity\\":\\"10\\",\\"Price\\":\\"10\\",\\"Type\\":\\"InventoryItem\\"},{\\"Product\\":\\"ProductTwo\\",\\"Quantity\\":\\"100\\",\\"Price\\":\\"20\\",\\"Type\\":\\"InventoryItem\\"}],\\"Type\\":\\"Inventory\\"}";

//将JSON文本转换为对象，并将一般类的实例改成伪类的实例。  
var inventoryObject = JSON.parse(inventoryJSONText, function(key, value) {  
   var type;  
   if (value && typeof value === 'object') {  
      type = value.Type;  
      if (typeof type === 'string' && typeof window\[type] === 'function') {  
         return new (window\[type])(value);  
      }  
   }  
   return value;  
});

//输出转换后对象的信息。  
var output = "Product\\t\\tQuantity\\tPrice\\tTotal\\n";  
for (var key in inventoryObject.Item) {  
   var item = inventoryObject.Item\[key];  
   output += item.Product + "\\t" + item.Quantity + "\\t\\t" + item.Price + "\\t" + item.Total() + "\\n";  
}  
output += "\\t\\t\\t\\t\\t" + inventoryObject.Total();  
alert(output);

//再将inventoryObject对象转换成JSON文本。  
var inventoryJSONTextAgain = JSON.stringify(inventoryObject, null, 3);  
alert(inventoryJSONTextAgain);  
&lt;/script&gt;

转载：[http://www.olnote.com/itlife/note/100000091.html](http://www.olnote.com/itlife/note/100000091.html)