The JavaScript JSON Cookbook - Ray Rischpater - E-Book

The JavaScript JSON Cookbook E-Book

Ray Rischpater

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

If you're writing applications that move structured data from one place to another, this book is for you. This is especially true if you've been using XML to do the job because it's entirely possible that you could do much of the same work with less code and less data overhead in JSON.
While the book's chapters make some distinction between the client and server sides of an application, it doesn't matter if you're a frontend, backend, or full-stack developer. The principles behind using JSON apply to both the client and the server, and in fact, developers who understand both sides of the equation generally craft the best applications.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 232

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Reading and Writing JSON on the Client
Introduction
Reading and writing JSON in JavaScript
Getting ready
How to do it...
How it works...
There's more...
Reading and writing JSON in C++
Getting ready
How to do it...
How it works...
See also
Reading and writing JSON in C#
Getting ready
How to do it...
How it works...
There's more...
See also
Reading and writing JSON in Java
Getting ready
How to do it...
There's more…
See also
Reading and writing JSON in Perl
How to do it...
How it works...
See also
Reading and writing JSON in Python
Getting ready
How to do it...
How it works...
See also
2. Reading and Writing JSON on the Server
Reading and writing JSON in Clojure
Getting ready
How to do it...
There's more...
Reading and writing JSON in F#
Getting ready
How to do it...
How it works...
There's more...
Reading and writing JSON with Node.js
Getting ready
How to do it...
See also
Reading and writing JSON in PHP
How to do it...
Reading and writing JSON in Ruby
Getting ready
How to do it...
See also
3. Using JSON in Simple AJAX Applications
Introduction
Setting up the server
Setting up the client page
Creating an XMLHttpRequest object
How to do it...
How it works…
See also
Making an asynchronous request for data
How to do it...
How it works…
See also
Sending JSON to your web server
How to do it...
How it works…
Accepting JSON using Node.js
How to do it...
How it works…
See also
Getting the progress of an asynchronous request
How to do it...
How it works…
There's more...
See also
Parsing the returned JSON
How to do it...
How it works…
There's more...
Issuing a web service request using Node.js
Getting ready
How to do it...
How it works…
There's more...
See also
4. Using JSON in AJAX Applications with jQuery and AngularJS
Introduction
Adding a dependency to jQuery to your web page
How to do it...
How it works…
There's more…
See also
Requesting JSON content using jQuery
How to do it...
How it works…
See also
Sending JSON to your web server using jQuery
How to do it...
How it works…
Getting the progress of a request using jQuery
How to do it...
How it works…
There's more...
Parsing the returned JSON using jQuery
How to do it...
How it works…
There's more...
Adding a dependency to AngularJS to your web page
How to do it...
How it works…
See also
Requesting JSON content using AngularJS
How to do it...
How it works…
There's more...
See also
Sending JSON to your web server using AngularJS
How to do it...
How it works…
There's more...
Getting the progress of a request using AngularJS
How to do it...
How it works…
Parsing the returned JSON using AngularJS
How to do it...
How it works…
5. Using JSON with MongoDB
Introduction
Setting up MongoDB
How to do it…
How it works…
Installing the MongoDB database driver for Node.js
How to do it…
Installing the express module for Node.js
How to do it…
How it works…
See also
Connecting to a MongoDB database using Node.js
How to do it...
How it works…
See also
Creating a document in MongoDB using Node.js
How to do it...
How it works…
There's more
See also
Searching for a document in MongoDB with Node.js
How to do it...
How it works…
There's more
See also
Updating a document in MongoDB with Node.js
How to do it...
How it works…
There's more…
See also
Deleting a document in MongoDB using Node.js
How to do it...
How it works…
See also
Using REST to search MongoDB
How to do it...
How it works…
There's more
Using REST to create a document in MongoDB
How to do it...
How it works…
Using REST to update a document in MongoDB
How to do it...
How it works…
Using REST to delete a document in MongoDB
How to do it...
How it works…
6. Using JSON with CouchDB
Introduction
Installing and setting up CouchDB and Cradle
How to do it…
How it works…
See also
Connecting to a CouchDB database using Node.js and Cradle
How to do it...
How it works…
Creating a CouchDB database using Node.js and Cradle
How to do it...
How it works…
There's more…
Creating a document in CouchDB using Node.js and Cradle
How to do it...
How it works…
Setting up a data view in CouchDB with Node.js and Cradle
How to do it...
How it works…
See also
Searching for a document in CouchDB with Node.js and Cradle
How to do it...
How it works…
There's more
See also
Updating a document in CouchDB with Node.js and Cradle
How to do it...
Deleting a document in CouchDB using Node.js and Cradle
How to do it...
There's more…
Using REST to enumerate CouchDB records
How to do it...
How it works…
See also
Using REST to search CouchDB
How to do it...
How it works…
Using REST to upsert a document in CouchDB
How to do it...
How it works…
Using REST to delete a document in CouchDB
How to do it…
How it works…
7. Using JSON in a Type-safe Manner
Introduction
How to deserialize an object using Json.NET
Getting ready
How to do it…
How it works…
There's more…
See also
How to handle date and time objects using Json.NET
How to do it…
How it works…
There's more…
See also
How to deserialize an object using gson for Java
Getting ready
How to do it…
How it works…
There's more…
See also
How to use TypeScript with Node.js
How to do it…
There's more…
See also
How to annotate simple types using TypeScript
How to do it…
How it works…
There's more…
See also
How to declare interfaces using TypeScript
How to do it…
How it works…
There's more…
See also
How to declare classes with interfaces using TypeScript
How to do it…
How it works…
See also
Using json2ts to generate TypeScript interfaces from your JSON
How to do it…
How it works…
8. Using JSON for Binary Data Transfer
Introduction
Encoding binary data as a base64 string using Node.js
How to do it…
How it works…
See also
Decoding binary data from a base64 string using Node.js
Getting ready
How to do it…
How it works…
See also
Encoding and decoding binary data as a base64 string using JavaScript in the browser
How to do it…
How it works…
See also
Encoding data as BSON using Json.NET
Getting ready
How to do it…
How it works…
See also
Decoding data from BSON using Json.NET
Getting ready
How to do it…
How it works…
There's more…
See also
Using a DataView to access an ArrayBuffer
Getting ready
How to do it…
How it works…
See also
Encoding and decoding base64 using an ArrayBuffer
How to do it…
How it works…
Compressing object-body content from a Node.js server built using the express module
Getting ready
How to do it…
How it works…
9. Querying JSON with JSONPath and LINQ
Introduction
Using the JSONPath dot-notation to query JSON documents
How to do it…
How it works…
There's more…
See also
Using JSONPath bracket-notation to query JSON documents
How to do it…
How it works…
Using JSONPath scripting to construct more complicated queries
How to do it…
How it works…
Using JSONPath in your web application
Getting ready
How to do it…
How it works…
See also
Using JSONPath in your Node.js application
Getting ready
How to do it…
How it works…
See also
Using JSONPath in your PHP application
Getting ready
How to do it…
How it works…
See also
Using JSONPath in your Python application
Getting ready
How to do it…
How it works…
See also
Using JSONPath in your Java application
Getting ready
How to do it…
How it works…
There's more…
See also
Using JSONPath with SelectToken to query for JSONPath expressions in your C# application
Getting ready
How to do it…
How it works…
See also
Using LINQ with Json.NET to query JSON in your C# application
Getting ready
How to do it…
How it works…
See also
10. JSON on Mobile Platforms
Introduction
Parsing JSON on Android
How to do it…
How it works…
There's more…
See also
Generating JSON on Android
How to do it…
How it works…
There's more…
See also
Parsing JSON on iOS in Objective-C
How to do it…
How it works…
There's more…
See also
Generating JSON on iOS in Objective-C
How to do it…
How it works…
See also
Parsing JSON on iOS using Swift
How to do it…
How it works…
Generating JSON on iOS using Swift
How to do it…
How it works…
Parsing JSON using Qt
How to do it…
How it works…
There's more…
See also
Generating JSON using Qt
How to do it…
How it works…
See also
Index

JavaScript JSON Cookbook

JavaScript JSON Cookbook

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: June 2015

Production reference: 1230615

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-690-2

www.packtpub.com

Credits

Author

Ray Rischpater

Reviewers

Vipul A M

Robert MacLean

Charlotte Spencer

Commissioning Editor

Amarabha Banerjee

Acquisition Editors

Manish Nainani

Llewellyn Rozario

Content Development Editor

Susmita Sabat

Technical Editor

Ankur Ghiye

Copy Editor

Adithi Shetty

Project Coordinator

Suzanne Coutinho

Proofreader

Safis Editing

Indexer

Priya Sane

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

About the Author

Ray Rischpater is an engineer and author with over 20 years of experience in writing about and developing for mobile computing platforms.

During this time, he participated in the development of Internet technologies and custom applications for Java ME, Qualcomm BREW, Apple iPhone, Google Android, Palm OS, Newton, and Magic Cap, as well as several proprietary platforms. Currently, he's employed as a software development manager at Microsoft in Sunnyvale, where he works on mapping and data visualization.

When he is not writing about software development, he enjoys hiking and photography with his family and friends in and around the San Lorenzo Valley in Central California. When he can, he also provides public service through amateur radio as the licensed Amateur Extra station KF6GPE.

Among the books he's written are Application Development with Qt Creator (now in its second edition, published by Packt Publishing, 2014) and Microsoft Mapping (with Carmen Au, published by Apress, 2013). Ray also irregularly blog at http://www.lothlorien.com/kf6gpe.

Ray holds a bachelor's degree in pure mathematics from the University of California, Santa Cruz, and is a member of the IEEE, ACM, and ARRL.

About the Reviewers

Vipul A M works as a software developer at BigBinary LLC. He is an avid Rails on Ruby projects contributor. He spends his spare time exploring and contributing to many open source Ruby projects when not dabbling with ReactJS or creating various screencasts.

He is currently working on a book titled ReactJS by Example, which walks you through how to use ReactJS, while working on project examples.

Vipul loves Ruby's vibrant community and helps in building PuneRb. He is the founder of and runs the RubyIndia Community newsletter and RubyIndia podcast and organizes the Deccan Ruby Conference in Pune. He blogs prolifically at blog.bigbinary.com and loves doing various screencasts at videos.bigbinary.com.

Robert MacLean has been working for over 18 years as a developer and an IT professional in South Africa, where he worked on a wide variety of projects with a number of customers. Today, he works as a developer at Microsoft, developing applications for Windows platforms.

Charlotte Spencer is a frontend web developer with a keen interest in semantic HTML, progressive enhancement, and accessibility. When they're not programming, they are writing about the Web and her experiences with it, reading, or preparing for the zombie apocalypse. They tweets at @charlotteis.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

JavaScript Object Notation (JSON) has rapidly become the lingua franca for structured document exchange on the Web, outpacing XML in many domains. Three of the reasons for this are obvious: it plays well with JavaScript, it's simple, and it just works. However, there are other reasons for its success as well. As you'll see in the pages of this book, it's supported by a wide variety of languages and libraries, making it easy to use in all kinds of scenarios.

In this book, I provide recipes for common uses of JSON. You're welcome to read the book from cover to cover, seeing all the ways JSON can be used in building web and standalone applications. However, it's organized as a cookbook, so that you can quickly go to the chapter or recipe that addresses a particular problem you might want to solve with JSON now. I recommend skimming this preface to see what's where, taking a quick look at Chapter 1, Reading and Writing JSON on the Client, or Chapter 2, Reading and Writing JSON on the Server, depending on your interest, and then jumping right to the recipes that interest you the most.

What this book covers

Chapter 1, Reading and Writing JSON on the Client, gives you recipes to read and write JSON in a number of client environments, including JavaScript, C#, C++, Java, Perl, and Python.

Chapter 2, Reading and Writing JSON on the Server, goes the other way, looking at JSON on typical server-side languages such as Clojure, C#, Node.js, PHP, and Ruby. Of course, you can write client-side applications with these languages, as well, just as you can write a server in C# or Java. So the division of recipes between these chapters is somewhat arbitrary; pick a language and dive in!

Chapter 3, Using JSON in Simple AJAX Applications, shows you how to apply JSON for data exchange with today's browsers.

Chapter 4, Using JSON in AJAX Applications with jQuery and AngularJS, discusses how to use JSON with two popular web frameworks, jQuery and Angular.

Chapter 5, Using JSON with MongoDB, shows you how MongoDB, a popular NoSQL database, uses JSON for its stored document format and gives you recipes to use MongoDB as a REST service in your web applications.

Chapter 6, Using JSON with CouchDB, shows you how CouchDB, another popular NoSQL database, uses JSON and how you can use CouchDB as a standalone REST service in your web applications.

Chapter 7, Using JSON in a Type-safe Manner, looks at how you can adapt the type-free nature of JSON with the type safety provided by languages such as C#, Java, and TypeScript to reduce programming errors in your application.

Chapter 8, Using JSON for Binary Data Transfer, shows you how, even though JSON is a text-based document format, you can still use it to move binary data around if you have to do so.

Chapter 9, Querying JSON with JSONPath and LINQ, has recipes on how you can write queries against JSON documents to obtain just the slice of data you're looking for. This is especially powerful when combined with the recipes from Chapters 5, Using JSON with MongoDB, and Chapter 6, Using JSON with CouchDB.

Chapter 10, JSON on Mobile Platforms, shows you recipes for using JSON in mobile applications that use Android, iOS, and Qt.

What you need for this book

Unlike many other technical books, this one focuses on a wide variety of supporting technologies in its examples. I don't expect that you'll have experience or the tools to try every example in this book, especially right away. However, it's helpful to have a few things set out.

You should have some programming experience, preferably in JavaScript. Unless a recipe is targeted at a specific programming language such as C#, the recipes in this book are written in JavaScript. I do this for two reasons. Firstly because the "J" in JSON stands for JavaScript (even though it's widely applicable to other languages), and, in this day and age, every programmer should have at least a nodding familiarity of JavaScript.

As far as software environments go, to begin with, you should have access to a good web browser such as Chrome or a recent version of Safari, Firefox, or Internet Explorer. You can use the JavaScript runtime in any of these browsers to experiment with JSON and get started.

Secondly, a lot of the client-server examples feature Node.js. I picked Node.js for server-side example programming because it's also JavaScript, meaning that you don't have to jump through different language syntaxes as you move between the client and server. Node.js runs well on Windows, Mac OS X, and Linux, too, so you shouldn't have a problem setting it up.

If you're interested in using JSON with databases, CouchDB or MongoDB are your best choices and I discuss both of them in this book. Which one you choose is really a matter of your domain and personal preference. I've been using MongoDB for 5 years on various projects but have recently taken a liking to some of CouchDB's features and its integrated support for RESTful services.

Finally, if you're a Microsoft developer, you may want to take special note of the C# examples that use Newtonsoft's Json.NET throughout this book. Json.NET is what JSON in C# ought to be, and it's definitely worth your attention.

Who this book is for

If you're writing applications that move structured data from one place to another, this book is for you. This is especially true if you've been using XML to do the job because it's entirely possible that you could do much of the same work with less code and less data overhead in JSON.

While the book's chapters make some distinction between the client and server sides of an application, it doesn't matter if you're a frontend, backend, or full-stack developer. The principles behind using JSON apply to both the client and the server, and in fact, developers who understand both sides of the equation generally craft the best applications.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Let's look at loads and dumps further."

A block of code is set as follows:

function doAjax() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

function doAjax() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } }

Any command-line input or output is written as follows:

# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: " Then, you'll want to go to More Tools | JavaScript console."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the ErrataSubmissionForm link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Reading and Writing JSON on the Client

In this chapter, we will cover the following recipes:

Reading and writing JSON in JavaScriptReading and writing JSON in C++Reading and writing JSON in C#Reading and writing JSON in JavaReading and writing JSON in PerlReading and writing JSON in Python

In addition to reading and writing JSON in Python, we will begin by showing you a brief review of JSON formatting to help set the stage for what follows in this book.

Introduction

JSON stands for JavaScript Object Notation. It's an open standard to represent data as attributes with values. Originally derived from the JavaScript syntax (hence its name) for use in web applications as an alternative to the more verbose and structured Extensible Markup Language (XML), it is now used for data serialization and transport in many standalone and web applications.

JSON provides an ideal means to encapsulate data between the client and server. In this first chapter, you will learn how to work with JSON in languages specified at the beginning of this chapter.

These languages are often used for client-side development, which is what we will focus on here. We'll look more at server-side languages in Chapter 2, Reading and Writing JSON on the Server.

Let's take a look at some JSON returned by the web API, available at http://www.aprs.fi, and modified a bit by me to make the example clear (later, in Chapter 4, Using JSON in AJAX Applications with jQuery and AngularJS, you'll learn how to fetch this data yourself using a web browser and JavaScript):

{ "command":"get", "result":"ok", "what":"loc", "found":2, "entries":[ { "class":"a", "name":"KF6GPE", "type":"l", "time":"1399371514", "lasttime":"1418597513", "lat":37.17667, "lng":-122.14650, "symbol":"\/-", "srccall":"KF6GPE", }, { "class":"a", "name":"KF6GPE-7", "type":"l", "time":"1418591475", "lasttime":"1418591475", "lat":37.17633, "lng":-122.14583, "symbol":"\\K", "srccall":"KF6GPE-7", } ] }

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

There are a few things to notice about this example:

The data is organized into attributes and values, each separated by a colon. (Note that a JSON document can also be a single value, such as a string, float, integer, or Boolean value.)Attributes appear as character strings enclosed by double quotes on the left-hand side of a colon.Values are on the right side of the colon and can be the following:
Character strings (enclosed in double quotes) such as KF6GPENumbers (either integers or floating point) such as 2 or 37.17667