Statistics
44
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-12-03
Support
Share

AuthorBen Smith

JSON (javascript Object Notation) — текстовый формат обмена данными, основанный на javascript. Beginning JSON is the definitive guide to JSON - todays standard in data formatting for the web. The book starts with the basics, and walks you through all aspects of using the JSON format.

Tags
No tags
ISBN: 1484202031
Publisher: Apress
Publish Year: 2015
Language: 英文
Pages: 324
File Format: PDF
File Size: 7.1 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Beginning JSON Ben Smith
Beginning JSON Copyright © 2015 by Ben Smith This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. ISBN-13 (pbk): 978-1-4842-0203-6 ISBN-13 (electronic): 978-1-4842-0202-9 Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image, we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the author nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director: Welmoed Spahr Lead Editor: Ben Renow-Clarke Technical Reviewer: Victor Sumner Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan, Jim DeWolf, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Steve Weiss Coordinating Editor: Christine Ricketts Copy Editor: Michael G. Laraque Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer- sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail rights@apress.com, or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales– eBook Licensing web page at www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/.
To my wife, for her patience with the late evenings and stay-at-home weekends, as well as for her constant encouragement
Contents at a Glance About the Author About the Technical Reviewer Acknowledgments Introduction Chapter 1: JavaScript Basics Chapter 2: Special Objects Chapter 3: String Manipulation Chapter 4: Introducing JSON Chapter 5: Creating JSON Chapter 6: Parsing JSON Chapter 7: Persisting JSON: I Chapter 8: Data Interchange Chapter 9: X-Origin Resources Chapter 10: Serving JSON Chapter 11: Posting JSON Chapter 12: Persisting JSON: II Chapter 13: Working with Templates Chapter 14: Putting It All Together Index
Contents About the Author About the Technical Reviewer Acknowledgments Introduction Chapter 1: JavaScript Basics JavaScript History JavaScript Essentials Values Primitive Types Expressions Operators Statements Line Terminators Control Statements Block Statements Truthy/Falsy Loop Statements Declarations Variables Functions Summary Key Points from This Chapter Chapter 2: Special Objects Objects Objects Are Collections Built-in Objects Object Creating Objects Access Notation
Array Object Literals Designing Literals The Object Literal The Array Literal Summary Key Points from This Chapter Chapter 3: String Manipulation String Concatenation The String object Creating String objects The Interface of the String object length toString charAt indexOf lastIndexOf match replace slice substr split toUpperCase toLowerCase The Implicit String object Summary Key Points from This Chapter Chapter 4: Introducing JSON History JSON Grammar Composite Structures JSON Values JSON Tokens
Summary Key Points from This Chapter Chapter 5: Creating JSON The Serialization Process—Demystified The JSON Object stringify Summary Key Points from This Chapter Chapter 6: Parsing JSON JSON.parse eval reviver Summary Key Points from This Chapter Chapter 7: Persisting JSON: I HTTP Cookie Syntax document.cookie Web Storage Web Storage Interface Summary Key Points from This Chapter Chapter 8: Data Interchange Hypertext Transfer Protocol HTTP-Request HTTP Response Ajax XMLHttpRequest Interface Global Aspects The Request Aspect The Response Aspect Obtaining the Response
Summary Key Points from This Chapter Chapter 9: X-Origin Resources Same-Origin Policy Circumventing Same-Origin Policy CORS The Proxy JSONP Summary Key Points from This Chapter Chapter 10: Serving JSON Node.JS Windows Installation Mac Installation Building an HTTP Server Node HTTP Web Server Node API Modules The HTTP Module http.createServer http.IncomingMessage http.ServerResponse http.Server CORS-Enabled Server JSONP Server The Proxy Server http.request http.Stream http.ClientRequest Summary Key Points from This Chapter Chapter 11: Posting JSON Request Entity Body
HTML Form POST Processing a JSON POST Preflight Request OPTIONS Request Method What Determines Preflight Summary Key Points from This Chapter Chapter 12: Persisting JSON: II CouchDB Windows Installation Mac Installation Working with CouchDB Futon Creating Views Creating Our First Custom View Connecting Node and CouchDB Cradle for Node Working with Databases Cradle Database API Creating Documents via Cradle Creating Design Documents via Cradle Summary Key Points from This Chapter Chapter 13: Working with Templates Templating Engine Handlebars Installation Working with Handlebars A Basic Expression The Role of <script> Compiling a Template Giving Context to Our Template Multiple Placeholders Complex JSON Structures Block Expressions
Block Expressions and Arrays Applying Logic to Logic-less Templates Helpers Summary Key Points from This Chapter Chapter 14: Putting It All Together Twitter Twitter Apps Keys and Access Tokens Public Stream Your User Access Token #Trending Node.js Twitter Module Incorporating the Twitter Module Streaming API (Stable) Statuses/Filter CouchDB Incorporating the Cradle Module Creating a View Enabling CORS Ajax Requesting Ranges Handlebars Summary Index
About the Author Ben Smith is an accomplished technical experience director with many years of experience leading web development for well-known digital agencies. His list of contributions to the community has earned him a place as an Adobe Community Professional. It should be apparent from his background as an author, speaker, and a judge for the Favourite Website Awards (FWA) that he is passionate about the Web. He attributes his growth to experimentation and experience.
About the Technical Reviewer Victor Sumner is a senior software engineer at D2L Corporation, where he helps to build and maintain an integrated learning platform. As a self-taught developer, he is always interested in emerging technologies and enjoys working on and solving problems that are outside his comfort zone. When not at the office, Victor has a number of hobbies, including photography, horseback riding, and gaming. He lives in Ontario, Canada, with his wife, Alicia, and their two children.
Acknowledgments This book could not have been written without a loving and patient wife, an understanding circle of friends, and a great team of editors and reviewers. My sincerest thanks to them all.
Introduction Programming is not at all a linear path. Often, you find yourself facing a fork in the road. In choosing one path, you are likely to find, after a period of time, that you go back and travel down the other. While it is assumed that you are familiar with HTML, CSS, and JavaScript, this book makes no further assumptions regarding your experience. Therefore, it attempts to provide a thorough explanation for everything you will read in it. While JSON is the essence of this book, it is not the sole topic discussed. While that may sound counterproductive, it is a much-needed requirement. JSON can be devised in isolation, but it would serve little purpose. What makes JSON so impactful is that it interacts with the many tools of the developer. For this reason, this book covers a wide range of implementations—from libraries to software.
CHAPTER 1 JavaScript Basics JavaScript is a scripting language that has been known to be a finicky beast. Many well- known developers have forged their names in the annals of the web-development community, having discovered special techniques and hidden gems to tame said beast. The topic of this book, JSON, is one such gem. You will learn more about that in Chapter 4. JSON is simply a data-interchange format and, therefore, does not directly require immediate knowledge of the JavaScript language. However, this book does not only discuss the composition of JSON. It also discusses how to incorporate it within an application. For this reason, this book employs JavaScript extensively to demonstrate the many ways to work with JSON. There are plenty of great books that reveal the ins and outs of the JavaScript language. This chapter solely acts as a primer to the upcoming chapters. JavaScript History The year is 1995, and Netscape seeks to add dynamic behavior as well as the capability to automate parts of a web page within its browser. It was at this point in time that Brendan Eich was hired to incorporate the functional scripting language Scheme into the Netscape Navigator browser.1 However, Netscape had also been in discussion with other software/hardware companies. In a mad dash for the finish line, Eich had prototyped the scripting language that would soon become what is known today as JavaScript. The incorporation of this new dynamic behavior within the browser became a game- changer. This had a direct impact on how developers programmed for the Web. Furthermore, this incorporation, as an innovation, encouraged Internet users to adopt Navigator as the preferred browser. In order to compete with the new dynamic, and with the browser wars on the rise, Microsoft was quick to incorporate a scripting language of its own into Internet Explorer. Microsoft’s scripting dialect was developed to be compatible with the scripting language of Netscape. However, to ensure the language remained uniform, Netscape submitted its dialect to the Ecma International for standardization. Thus were the beginnings of the ECMA-262 specification. ECMA-262 is the name for this scripting language’s specification. The name ECMAScript is the union of Ecma International and JavaScript. To reference ECMAScript is to reference the specification rather than the language itself. JavaScript Essentials
At its core, JavaScript is a text-based scripting language, whereby sequences of Unicode characters are strung together. That said, what makes JavaScript more than a sequence of characters is its adherence to the rules that govern how the JavaScript engine interprets said sequence into a particular application. The set of rules that defines the valid sequencing of characters is known as Syntax. Listing 1-1 reveals a syntactically correct, albeit simple, JavaScript application. Listing 1-1. A Valid JavaScript Program 1 var welcomeMessage = "Hello World"; 2 //Lines denoted with '//' are used to leave comments 3 console.log( welcomeMessage ); //prints to the console Hello World 4 console.log("A"); //prints the character A 5 console.log( 2+5 ); //prints the number 7 6 7 console.log("goodbye" + " " + "all"); //prints goodbye all. Listing 1-1 reveals seven lines composed of a sequence of Unicode-encoded characters. However, as the characters of Listing 1-1 adhere to the ECMAScript specification, what Listing 1-1 reveals is technically a JavaScript application. Values Because many languages heavily influenced JavaScript, the values used by JavaScript may appear familiar. While there are many values used by the JavaScript language, there are two categories for which these values are distinguished. Those two categories are the primitive and non-primitive types. Non-primitive types are otherwise known as Objects and are the topic of Chapter 2. Primitive Types A primitive type represents the set of all basic building blocks for which data can be represented. These are referred to as primitive because they are rudimentary. This is, of course, in contrast to non-primitive types. There are five primitive types in JavaScript, as depicted in Figure 1-1. These five types are number, string, Boolean, undefined, and null. Figure 1-1. The five primitive types in JavaScript
The Number Type The number type represents the set of all possible numeric values recognized by the JavaScript language. Such representations are shown in Figure 1-2. Possible number values include fractions as well as whole numbers, and each can possess a negative or positive value. Additionally, fractions can be written using scientific notation. Listing 1-2 reveals a variety of valid JavaScript numeric values. Figure 1-2. Valid representations of the number type Listing 1-2. Valid Number Values 4 16 3.402823669209385e+38 -1 The String Type The string type represents the set of all possible string values whereby a string value is a finite representation that includes 0 or more Unicode characters. As outlined in Figure 1-3, while the character encoding is strictly regarded as that of Unicode, string values can also be representative of ASCII character encoding. This is because ASCII is a subset of the Unicode character set. Examples of possible string values can be found in Listing 1-3. Figure 1-3. Valid encodings of the string type Listing 1-3. Valid String Values "this is a string value"; "string"; "s"; ""; //An empty String Because a program is made up of text, a string value is differentiated from our program by delimiting its value with quotations. In Listing 1-3, I have wrapped each string value within double quotes. However, it is entirely valid to utilize singular quotes as well. Because quotations mark the beginning and end of a string value, it will be imperative that your string does not employ the same outer quotes to nest quotes such as the
following: “Mike said and I quote, “let me tell you a secret””. Nesting quotations with the same characters used to signify a string will confuse the engine, resulting in the likelihood of an error. Because the engine reads in a left-to-right, top-to-bottom manner, the first nested quotation encountered will be interpreted as the terminating quotation. This means that what was expected to be a quote by Mike is instead treated as an invalid statement. Nesting quotations within string values are perfectly acceptable, providing they do not cause the engine to believe the string ends prematurely, as in the preceding example. There are two possible ways to accomplish this. Alternate Quotations Because you can alternate between singular and double quotes, whichever you use to delimit a string value, you can use the alternate variation to add grammar to your string. Listing 1-4 revisits the preceding example with the use of alternating quotations. Listing 1-4. Alternating Use of Quotes 'Mike said and I quote, "let me tell you a secret".'; // ' is used to delimit a string "Mike said and I quote, 'let me tell you a secret'."; // " is used to delimit a string As you can see from Listing 1-4, you can use one pair of quotes to signify a string and an alternate form to establish proper English grammar within. The engine will interpret this as a string within a string and move on. Escaped Quotations The second method of incorporating quotes within a string is to ensure that the engine does not treat our inner quotations as string delimiters. In order to accomplish this, we must escape our inner quotation marks. The escape character instructs the engine to interpret the subsequent character differently from how it would otherwise be viewed. This is opposed to being interpreted as a delimiter that would otherwise be used to mark the end or beginning of a string value. Escaping a character is easily accomplished by prefixing the character you wish to escape with a backslash (\). The use of the escaped quotation allows our strings to employ quotations indiscriminately. Examples can be seen in Listing 1-5. Listing 1-5. Nested Escaped Quotations "Mike said and I quote, \"let me tell you a secret\"."; 'Mike said and I quote, \'let me tell you a secret\'.'; Note The escape character informs the engine to interpret a character differently. The Boolean Type
A Boolean type represents a logical value consisting of only two possible values. Those values, as illustrated in Figure 1-4, are either true or false. While these are two possible values that can be assigned, a Boolean type is commonly returned as the evaluation of a condition. Such an evaluation may be the comparison between two numbers, as seen in Listing 1-6. Figure 1-4. Valid values of the Boolean type Listing 1-6. Boolean Expressions var bol = false; //assigns bol a false value (10<9); //evaluates to false; (10>9); //evaluates to true; Boolean values are great for incorporating decision making within your application. Determining whether an expression evaluates to true or false allows an application to react accordingly. We will revisit this when I discuss conditional statements. undefined Type The undefined type is the value used to represent when an identifier has not yet been assigned a value. When a reference to a variable is evaluated, if it has yet to be assigned a value, the value of undefined is returned. Listing 1-7 reveals two lines of code. The first line is used to declare a variable labeled name (line 1). The declaration of our variable informs the JavaScript engine to allocate a portion of memory that our application can use to store data. The variable’s identifier name provides us a textual means to refer to said allocation. As we have not yet assigned any data to our variable, the subsequent line returns the value of undefined (line 2). Listing 1-7. An Undefined Variable 1 var name; 2 console.log(name) //returns undefined; null Type The null type represents the intentional absence of a value. This is contrary to the undefined value, which represents no value as having been set. The null type is a value used explicitly to represent an empty or nonexistent reference. Listing 1-8, assigns the value of null to the name identifier, to explicitly denote the intentional absence of a value. Listing 1-8. null Assignment
The above is a preview of the first 20 pages. Register to read the complete e-book.