为什么80%的码农都做不了架构师?>>>

JSON basics

At its simplest, JSON allows you to transform a set of data represented in a JavaScript object into a string that you can easily pass from one function to another, or -- in the case of asynchronous applications -- from a Web client to a server-side program. The string looks a little odd (you'll see some examples in just a moment), but it's easily interpreted by JavaScript, and JSON allows you to represent structures more complex than name/value pairs. For instance, you can represent arrays and complex objects, rather than just simple lists of keys and values.

Simple JSON examples

At its very simplest, you can represent what is essentially a name/value pair in JSON like this:

{ "firstName": "Brett" }

This is pretty basic and actually takes up more space than the equivalent name/value pair in clear text:

firstName=Brett

However, JSON illustrates its value when you start to string together multiple name/value pairs. First, you can create what is essentially a record of data, with multiple name/value pairs, like this:

{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }

There's still not much advantage here over name/value pairs in terms of syntax, but in this case JSON is significantly easier to use, and has some readability advantages. For example, it's clear that all three of the values above are part of the same record; the brackets establish that the values have some connection.

Arrays of values

When you need to represent a set of values, JSON starts to be not only more readable, but less verbose. Say, for example, that you want to have a list of people. In XML, you'd be stuck with lots of opening and closing tags, and if you were using typical name/value pairs -- the kind we've looked at in earlier articles in this series -- then you'd have to come up with a proprietary data format, or perhaps modify the key names to something like person1-firstName.

With JSON, you can simply group multiple bracketed records:

{ "people": [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
]}

This isn't too hard to understand. In this case, there's a single variable, named people, and the value is the array containing three items, each of which is a person record with a first name, a last name, and an e-mail address. The example above illustrates how you can throw records together, and also group the items into a single value with brackets around it. Of course, you could use the same syntax, but have multiple values (each with multiple records):

{ "programmers": [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }],
"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" }]
}

The most obvious thing to note here is your ability to represent multiple values that each in turn have multiple values. What you should also notice, though, is that the actual name/value pairs in the records change across the different main entries (programmers, authors, and musicians). JSON is completely dynamic and lets you change the way you represent data in the middle of your JSON structure.

To put it another way, there is no predefined set of constraints that you need to follow when working with JSON-formatted data. So you can change how you represent things, or even represent the same thing in different ways, all within the same data structure.

Back to top

Using JSON in JavaScript

After you've got a handle on the JSON format, it's simple to use it within JavaScript. JSON is a native JavaScript format, meaning simply that you don't need any special API or toolkit to work with JSON data within JavaScript.

Assigning JSON data to a variable

For example, you can simply create a new JavaScript variable and then directly assign a string of JSON-formatted data to it:

var people ={ "programmers": [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }],"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" }]}

There's nothing complicated going on here; now people contains the JSON formatted data we've been looking at throughout this article. However, this doesn't do much, as the data still isn't in a format that is obviously useful.

Accessing the data

While it might not be obvious, that lengthy string above is just an array, and once you've got that array in a JavaScript variable, you can access it easily. In fact, you can simply separate the array with period delimiters. So, to access the last name of the first entry of the programmers list, you would use code like this in your JavaScript:

people.programmers[0].lastName;

Take note that the indexing is zero-based. So this begins with the data in the people variable; it then moves to the item calledprogrammers and pulls off the first record ([0]); finally, it accesses the value for the lastName key. The result is the string value "McLaughlin".

Here are a few more examples using the same variable.

people.authors[1].genre           // Value is "fantasy"people.musicians[3].lastName     // Undefined. This refers to the fourth entry,and there isn't onepeople.programmers.[2].firstName  // Value is "Elliotte"

With this little bit of syntax, you can work with any variety of JSON-formatted data, all without any extra JavaScript toolkits or APIs.

Modifying JSON data

Just as you can access data with the dot and bracket notation shown above, you can easily modify data in the same way:

people.musicians[1].lastName = "Rachmaninov";

That's all you need to do to change data in a variable once you've converted from a string to JavaScript objects.

Converting back to strings

Of course, all that data modification isn't of much value if you can't easily convert back into the textual format mentioned in this article. That's also trivial in JavaScript:

String newJSONtext = people.toJSONString();

That's all there is to it! Now you've got a string of text that you can use anywhere you like -- you could use it as the request string in an Ajax application, for instance.

Perhaps even more importantly, you can convert any JavaScript object into JSON text. You don't have to work only with variables that were originally assigned a JSON-formatted string. To transform an object named myObject, you would simply issue the same sort of command:

String myObjectInJSON = myObject.toJSONString();

This is the biggest difference between JSON and other data formats this series has explored. With JSON, you call a simple function and get your data, formatted and ready for use. With other data formats, it's your job to handle the conversion between the raw data and the formatted data. Even when using an API like the Document Object Model that provides a function that converts from its own data structure into text, you've got to learn the API and use that API's objects, rather than native JavaScript objects and syntax.

The end result is that when you're already working with lots of JavaScript objects, JSON is almost certainly a good bet for you to easily convert your data into a format that is simple to send in your requests to server-side programs.

转载于:https://my.oschina.net/zhenguoguan/blog/138749

Using JSON for data transfer相关推荐

  1. js 语法:JSON.stringify(data, null, 4)

    JSON.stringify(data, null, 4) JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串. JSON.stringify(data, ...

  2. 5G NR RLC:Data Transfer ARQ

    其他相关内容 RLC PDU and Parameters RLC架构和RLC entity 一 RLC entity handling RLC entity有建立.重建和释放的过程(establis ...

  3. 合理使用DTO(Data Transfer Object)

    文章目录 1. DTO简介 2. 到底什么是DTO? 3. 将DTO用作POJO 4. Java 中使用DTO的例子 5. 反例: 滥用DTO 6. 小结 相关链接 DTO, 全称为 Data Tra ...

  4. AS91创建历史资产卡片报错:消息号 FAA_MD036 segment 00001: Status ‘In Preparation‘; no data transfer possible

    文章目录 一.业务场景-AS91 二.问题分析和解决-FAA_CMP_LDT 一.业务场景-AS91 T-CODE: AS91 公司代码:2A00 参看详细信息 消息号 FAA_MD036 CoCd ...

  5. 天宝Trimble Data Transfer安装并传输数据

    天宝Trimble Data Transfer安装并传输数据 软件下载 问题描述 解决办法 软件下载 (若读者没有CSDN账号或者不方便下载,可以移步至本人同名博客园免费下载相关软件:https:// ...

  6. 使用AWS MVP方案[Data Transfer Hub]从Global S3同步文件到中国区S3

    本文主要描述在AWS Global区部署Data Transfer Hub方案,并创建从global S3同步文件到中国区S3的任务 本次实验架构图 1. 实验准备 1.1 AWS Global账号 ...

  7. 10.1 Converting json to data classes

    10.1 Converting json to data classes 处理json数据,是常见的工作,解析和处理json技术含量低,考验的是细心和耐心,原始的办法的就是对着json字符串一个一个的 ...

  8. WCF Data transfer buffered VS streamed

    WCF Data Transfer buffered VS streamed 在Data Transfer中,我们会经常听到开发提到buffer mode和stream mode.对于不了解Data ...

  9. Java DTO(data transfer object)的理解,为什么要用DTO

    DTO即数据传输对象. 现状 对于分布式系统,需要在不同系统之间传递与转换域对象.因为我们不希望外部公开内部域对象,也不允许外部域对象渗入系统.传统上,数据对象之间的映射通过手工编码(getter/s ...

最新文章

  1. mysql抑音符_MySQL-数据类型
  2. web项目Servlet配置及jsp访问Servlet
  3. 操作系统之进程管理:7、进程同步、进程互斥
  4. 家用电器用户行为分析与事件识别_数据产品指北:用户行为分析平台
  5. PHP利用GD库将微信小程序二维码和用户头像拼接且用户在微信服务号回复指定内容将拼接的二维码返回
  6. 软考高项-质量管理论文范文
  7. 用css制作网站首页
  8. 多传感器融合定位 第十章 基于优化的定位方法
  9. blackman窗 matlab,【matlab】矩形窗/三角窗/hanning窗/hamming窗/blackman窗的频率响应图...
  10. svn忽略不需要同步的文件夹_配置管理-SVN使用指南 - wuli潇潇
  11. 计算机关机键桌面,电脑关机快捷键是什么?
  12. 宽带未能和路由器连接服务器,连接路由器却上不了网怎么办
  13. 气泡文字php,HTML5实现对话气泡点击动画
  14. 天琴协议_天琴座:新秀背后
  15. 74HC02或非门仿真示例
  16. Archlinux双显卡安装NVIDIA闭源驱动
  17. eclipse Oxygen版本 安装cvs插件
  18. 思迈特软件Smartbi:10分钟教会你制作高难度的数据地图!
  19. Out-Of-Vocabulary(OOV)的理解
  20. R语言循环、连续检验

热门文章

  1. linux软件读取不到空间,Linux下Oracle软件、数据文件等所在的磁盘分区空间不足的解决思路...
  2. 树莓派 pip安装mysql_树莓派 pip 手动安装
  3. java客户端_Java常用的Http client客户端
  4. 各种抠图动态图片_不用手。自动、智能抠图,图片去背景
  5. jQuery 遍历:思路总结,项目场景中如何处理/控制获取的 each 遍历次数?
  6. java写一个99到0_Java中一个普通的循环为何从10开始到99连续相乘会得到0?
  7. linux ntp时间立即同步命令_记一次生产环境部署NTP服务及配置时间同步
  8. springboot2.0 redis EnableCaching的配置和使用
  9. lintcode 单词接龙II
  10. 5-数据结构-数组的学习