JavaScript is a general purpose programming language that was introduced as the page scripting language for Netscape Navigator. It is still widely believed to be a subset of Java, but it is not. It is a Scheme-like language with C-like syntax and soft objects. JavaScript was standardized in the ECMAScript Language Specification, Third Edition.

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

var myJSONObject = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};

In this example, an object is created containing a single member "bindings", which contains an array containing three objects, each containing "ircEvent", "method", and "regex" members.

Members can be retrieved using dot or subscript operators.

myJSONObject.bindings[0].method    // "newURI"

To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.

var myObject = eval('(' + myJSONtext + ')');

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

var myObject = JSON.parse(myJSONtext, reviver);

The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects.

myData = JSON.parse(text, 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;
});

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.

var myJSONText = JSON.stringify(myObject, replacer);

If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.

The stringifier method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text.

The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.

Values that do not have a representation in JSON (such as functions and undefined) are excluded.

Nonfinite numbers are replaced with null. To substitute other values, you could use a replacer function like this:

function replacer(key, value) {
if (typeof value === 'number' && !isFinite(value)) {
return String(value);
}
return value;
}

Giving a corresponding reviver to JSON.parse can undo that.

The open source code of a JSON parser and JSON stringifier is available. When minified it is less than 2.5K.

[转] json in javascript的更多相关文章

  1. 从Python传递JSON到JavaScript

    OS: Windows 8.1 with update 关键字:Python 3.4,HTML5,JSON,JavaScript 1.LocalServer.py,启动server,打开网页,传递JS ...

  2. javascript如何解析json对javascript如何解析json对象并动态赋值到select列表象并动态赋值到select列表

    原文 javascript如何解析json对象并动态赋值到select列表 JSON(JavaScriptObject Notation)一种简单的数据格式,比xml更轻巧.JSON是JavaScri ...

  3. json转javascript对象

    json转javascript对象var tpIdObj = eval("(" + tpid + ")");//json字符串转 对象var tpid = JS ...

  4. C#将XML转换成JSON 使用 JavaScript 将 XML 转成 JSON

    如何在ASP.NET中用C#将XML转换成JSON [JavaScript]代码 // Changes XML to JSON function xmlToJson(xml) { // Create ...

  5. JSON:JavaScript 对象表示法

    JSON:JavaScript 对象表示法(JavaScript Object Notation). JSON 是存储和交换文本信息的语法.类似 XML. JSON 比 XML 更小.更快,更易解析. ...

  6. JSON 在JavaScript 中的应用及自己的理解

    [对象和json]JSON:JavaScript 对象表示法(JavaScript Object Notation).JSON 是存储和交换文本信息的语法.类似 XML.JSON是一种数据格式,不是一 ...

  7. JSON和JavaScript对象

    var obj={width:100,height:200},这样的并不叫JSON,并且JSON只是一种数据格式,并不是具体的实例. 但很多人把这样的JS对象当成JSON,下面把这个问题讲清楚 一.J ...

  8. 5 JSON&与JavaScript转换&JavaScript:void(0)&JavaScript代码规范

    JSON:JavaScript Object Notation   JS对象简谱 一种轻量级的数据交换格式,用于存储和传输数据的格式,通常用于服务端向网页传递数据 是独立的语言,易于理解 JSON语法 ...

  9. JSON: JavaScript Object Notation

    JSON是JavaScript Object Notation 的缩写,是JS提供的一种数据交换格式.1) JSON对象本质上就是一个JS对象,但是这个对象比较特殊,它可以直接转换为字符串,在不同语言 ...

  10. json与JavaScript对象互换

    1,json字符串转化为JavaScript对象: 方法:JSON.parse(string) eg:var account = '{"name":"jaytan&quo ...

随机推荐

  1. Login过滤器

    继承自ActionFilterAttibute public override void OnActionExecuting(ActionExecutingContext filterContext) ...

  2. 使用SourceTree将bitbucket的远程仓库回滚到某一次提交-b

    目的: 使用SourceTree将bitbucket的远程仓库回滚到某一次提交. 原理: 在本地需要回滚的commit上创建一个分支,将该分支合并到远程仓库. 准备: 远程仓库有一个master主分支 ...

  3. 移动端meta标签整理-备

    分类 在介绍移动端特有 meta 标签之前,先简单说一下 HTML meta 标签的一些知识. meta 标签包含了 HTTP 标题信息 (http-equiv) 和 页面描述信息 (name). h ...

  4. 【转载】HRTF音频3D定位技术综述

    1. 序 您一定有过这样的经验:在一个炎热的夏夜,讨厌的蚊子在你的耳边飞舞.此时,没有比除掉这个祸害更急所的了,对吧?做到这一点,不必睁大了眼去找蚊子,只需依靠敏锐的听力,一样可以确定蚊子的方位,在漆 ...

  5. jQuery实现Twitter的自动文字补齐特效

    上图效果可以使用jQuery插件Typeahead.js来实现,这款jQuery插件来自于Twitter的一个新的项目,支持远程和本地的数据集.比较有特色的地方在于你可以将数据集使用本地存储(loca ...

  6. Android应用程序的生命周期

    转自Android应用程序的生命周期 在对一个简单的Hello World工程进行项目结构剖析后,我们接着来学习下一个Android应用程序的生命周期是怎么样的,以便为后面的开发有个垫下良好的基石~ ...

  7. Android 使用HttpClient方式提交GET请求

    public void httpClientGet(View view) { final String username = usernameEditText.getText().toString() ...

  8. Qt中连接到同一signal的多个slots的执行顺序问题(4.6以后按连接顺序执行)

    起源 前些天忘记在哪儿讨论过这个问题,今天在csdn又看到有网友问这个问题,而其他网友却无一例外的给出了“无序”这个答案. Manual Qt的问题,当manual中有明确文字说明时,我们应该以Qt的 ...

  9. 14.6.5 Configuring InnoDB Change Buffering 配置InnoDB Change Buffering

    14.6.5 Configuring InnoDB Change Buffering 配置InnoDB Change Buffering 当插入,更新,和删除操作在表上执行, 索引列的值(特别是 se ...

  10. Error: opening registry key 'Software\JavaSoft\Java Runtime Environment' Error: could not find java.dll

    java -jar yxCollector-1.1.0.jarError: opening registry key 'Software\JavaSoft\Java Runtime Environme ...