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,一经查实,立即删除!

相关文章

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之后的版本都应该…

NVelocity标签使用详解

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

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

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

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

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

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…

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文件,用虚拟光驱挂载或者解压运行,选择“安…

Ansible无敌详细入门教程

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

Nginx学习笔记(五) 源码分析内存模块内存对齐

Nginx源码分析&内存模块 今天总结了下C语言的内存分配问题,那么就看看Nginx的内存分配相关模型的具体实现。还有内存对齐的内容~~不懂的可以看看~~ src/os/unix/Ngx_alloc.h&Ngx_alloc.c 先上源码: /** Copyright (C) Igor Sysoev* Copyright (C…

reactor p java_Java反应式框架Reactor中的Mono和Flux

1. 前言最近写关于响应式编程的东西有点多,很多同学反映对Flux和Mono这两个Reactor中的概念有点懵逼。但是目前Java响应式编程中我们对这两个对象的接触又最多,诸如Spring WebFlux、RSocket、R2DBC。我开始也对这两个对象头疼,所以今天我们就…

Visual Studio 20xx试用版升级为正式版(WIN7同样有效)图解、附带序列号

Visual Studio 2005|2008 试用版升级为正式版(WIN7同样有效)。 目录 一、步骤图解 二、win7破解工具下载 三、序列号 一、步骤图解 1.控制面板 > 程序和功能 > Visual Studio 2005|2008 启动、修复程序。如图: 2.填写序列号&#xff0…

NHibernate使用之详细图解

本文档适合初级开发者或者是第一次接触NHibernate框架的朋友,其中NHibernate不是最新的版本,但是一个比较经典的版本 NHibernate 2.1.2,其中用红线标注的部分一定要仔细看,这些都是容易忽略和出错的地方,笔者在此给大家…

disabling directory browsing

2019独角兽企业重金招聘Python工程师标准>>> I have seen several recommendation to increase web application security by disabling directory browsing (for example pg 388 in IBM WebSphere Deployment and Advanced Configuration by Barcia, Hines, et al)…

水印生成器第2版[原图质量水印可自定义设置]

简介:水印生成器,原理很简单,一时在网上没有找到打水印的网站,自己便做了一个,效果如下图,可自定义字体大小、字体类型以及颜色。 开发环境:vs 2010 [net 3.5 WindowsForms应用程序] 本文带给…

服务发现与负载均衡traefik ingress

ingress就是从kubernetes集群外访问集群的入口,将用户的URL请求转发到不同的service上。Ingress相当于nginx、apache等负载均衡方向代理服务器,其中还包括规则定义,即URL的路由信息,路由信息得的刷新由 Ingress controller 提供 …

GentleNet使用之详细图解[语法使用增强版]

目录第一章 开发环境第二章 简介第三章 Gentle.Net-1.5.0 下载文件包介绍第四章 使用步骤第五章 源码下载 第一章、开发环境:Vs 2010 Sql 2005 GentleNet 1.5.0 【Web网站程序 .Net Framework 3.5】第二章、简介:Gentle.Net是一个开源的优秀O/R M…

NBear简介与使用图解

NBear简介与使用图解框架类型:ORM映射框架简介:NBear是一个基于.Net 2.0、C#2.0开放全部源代码的的软件开发框架类库。NBear的设计目标是尽最大努力减少开发人员的工作量,最大程度提升开发效率,同时兼顾性能及可伸缩性。Demo版本&…

搭建私有helm仓库及图形界面

搭建私有helm仓库及图形界面 本篇主要介绍私有 helm 仓库 Chartmuseum 及图形界面 Monocular UI /kubeapps 的搭建 helm chart 能够很好的封装和管理我们的 kubernetes 应用,可以实现中间件、数据库、公共组件等快速发布。 什么场景下我们需要构建一个私有的helm仓…

神啊,6小时30分钟,完成想要的所有Lync测试

神啊 !记住这个日子 !从未想到,6小时30分钟,能做出这么多东西:从:2013-06-28---20:00到2013-06-29-----2:30 (辛苦,也是值得,客户是上帝,公司也好,个人也罢&a…