Using JSON for data transfer

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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/547742.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

jquery的扩展方法介绍

最近一直在写js,这其中也少不了一位js的主角了jQuery,下面介绍的是jQuery的一些扩展,也就是jQuery的扩展方法,jQuery的扩展方法有两种方式,一种是jQuery本身的扩展方法,另一种是jQuery所选对象的扩展方法&a…

Gtk-WARNING : cannot open display----这个问题在NVIDIA TX2上碰到过就是DISPLAY=“:0“

切换到root权限,在终端下使用gedit时出现下面的错误: No protocol specified (gedit:14333): Gtk-WARNING **: cannot open display: :0.0 下面是从网上找到的正解,贴——分析——总结之: 原因: 当使用su 到另外一个用…

蓝桥杯vip答案java_Java实现 蓝桥杯VIP 算法训练 麦森数

算法训练 麦森数时间限制:1.0s 内存限制:256.0MB问题描述形如2P-1的素数称为麦森数,这时P一定也是个素数。但反过来不一定,即如果P是个素数,2P-1不一定也是素数。到1998年底,人们已找到了37个麦森数。最大的…

Visual Studio 2010 中JS注释制作

Visual Studio 2010中的js注释已经很强大了,但怎么才能和调用c#的方法一样容易呢?怎样才能让每个参数都有注释说明呢?底下就是想要的答案。 先上图,如图所示: 其中红色的办法为注释效果,当然制作的方法也在…

windows下配置caffe-matlab接口

一、环境说明 也是安装顺序。特别强调的是除VS2015以外,其他软件的安装路径都最好不要包含空格。 1、Windows 64位系统。 2、Visual Studio 2015(VS2015, 对应VC14)。 3、Matlab 2017a。Matlab的版本倒不是很重要,只要支持Matlab 2015a之后的版本都应该…

java在文档末尾添加_如何在打开表单后将子文件添加到Word文档的末尾?

我m trying to write a macro that adds subdocuments to the end of a Word document when the Word document is opened. The document in question already has some text in it, so before running the macro I d喜欢将光标移动到文档的末尾 . 我可以使用代码实现这一点&am…

oracle的db link

cd $ORACLE_HOME/network/admin vi tnsnames.ora 添加 CCPBS_19 (DESCRIPTION (ADDRESS_LIST (ADDRESS (PROTOCOL TCP)(HOST 10.130.38.19)(PORT 1521)) ) (CONNECT_DATA (SERVICE_NAME CCPBS) ) ) >create public database link ecbm_19 …

NVelocity标签使用详解

本文使用的NVelocity版本为1.1.1,应该是目前为止最新的版本吧,前几天在google上找了一个自称是NVelocity 1.6.1 bate2的dll,下载下来一看更新时间是2009年的,还没版本NVelocity 1.1.1(2010年出的) 新呢&…

一文搞懂蓝绿发布、灰度发布和滚动发布

一文搞懂蓝绿发布、灰度发布和滚动发布 应用程序升级面临最大挑战是新旧业务切换,将软件从测试的最后阶段带到生产环境,同时要保证系统不间断提供服务。 长期以来,业务升级渐渐形成了几个发布策略:蓝绿发布、灰度发布和滚动发布&…

NVelocity标签设置缓存的解决方案

意外的问题总会让人措手不及,今天与大家分享的就是NVelocity设置缓存的问题,之前刚google了一下发现没什么太好的解决方案,希望在这能为需要的朋友找出满意的答案,上一篇blog刚说了NVelocity的用法,这就不在重复了&…

实数历史无穷小能否带领我们直接走向今日科学之辉煌?

本篇文章朋友在深圳吃饭的时候突然想到的...这段时间就有想写几篇关于实数历史的博客,所以回家到之后就奋笔疾书的写出来发布了 历史不能重演,这是毫无疑问的。数学是一门基础学科,影响到本日科学技术的方方面面,可以说&#xff0…

java成员方法的一般格式为_Java基本知识(四)

一、二维数组1、定义方式m:代表当前二维数组中有多少个一维数组;n:代表每个一维数组的长度(1)数据类型[][] 数组名new 数据类型[m][n](2)数据类型[][] 数组名new 数据类型[m][ ],只给定m个一维数组,每个一维数组长度动…

免费的定时任务托管 clock.sh

自己有很多定时任务要跑,所以之前搞了一个定时运行的系统。 在 V2EX 看到很多有类似需求的朋友: https://www.v2ex.com/t/252810https://www.v2ex.com/t/448726https://www.v2ex.com/t/579740https://www.v2ex.com/t/241229https://hk.v2ex.com/t/1134…

Android Webservices 返回多行多列数据(Dataset)

对于之前从事.net或者java开发人员,习惯了从后台获取网格数据(多行多列DataTable),但转行从事android开发,难免会不习惯 Android调用Webservice时,如果返回值是一个boolean或者string值时可以通过下面方式接…

Spring.Net简单IOC应用

本文简单的介绍一下Spring.net的配置和IOC应用。 目录:  一、引用资源.  二、配置文件配置.  三、文件调用.  四、本实例代码下载(vs-2010). 一、引用资源(所需spring的dll) Spring.Core.dll Spring.Web.dll C…

vCenter Server Appliance(VCSA )6.7部署指南

VCSA 6.7版本于2018年4月17日提供下载,同时发布的还有ESXi 6.7,根据官方文档,6.7版本升级主要为了发布vSAN 6.7版本。 第1步,下载VMware-VCSA-all-6.7.0-8217866文件,用虚拟光驱挂载或者解压运行,选择“安…

学习的回顾--数组的有关内容

1、数组的定义以及简单的内容 C#中数组是引用类型,C#定义整型数组方式是:int [] intArray {1,2,3};或int [] intArray new int[10]; C#中的数组可以是一维的也可以是多维的,同样也支持矩阵和参差不齐的数…

mysql5.6.35安装_mysql5.6.35 二进制快速安装

说明:mysql安装在/data/mysql-5.6.35目录下;如果安装在/usr/local/mysql/目录下,则两个sed不许执行,因为默认是/usr/local/目录下;1.下载cd /data/tar -zxf mysql-5.6.35-linux-glibc2.5-x86_64.tar.gzmv mysql-5.6.35-linux-gli…

XML 通用操作

Xml格式&#xff1a; <?xml version"1.0" encoding"utf-8"?> <remotes> <remote ip"ipval">nameAndPwd</remote> </remotes> 通用读写删类&#xff1a; using System; using System.Data; using System.…

Ansible无敌详细入门教程

Ansible 是什么 ? ansible架构图 ansible特性 模块化&#xff1a;调用特定的模块&#xff0c;完成特定的任务&#xff1b; 基于Python语言研发&#xff0c;由Paramiko, PyYAML和Jinja2三个核心库实现&#xff1b; 部署简单&#xff1a;agentless&#xff1b; 支持自定义模…