| OLD | NEW |
| 1 --- | 1 --- |
| 2 layout: default | 2 layout: default |
| 3 title: "Fetch Data Dynamically" | 3 title: "Fetch Data Dynamically" |
| 4 description: "Use HttpRequest to fetch data from a file or a server." | 4 description: "Use HttpRequest to fetch data from a file or a server." |
| 5 has-permalinks: true | 5 has-permalinks: true |
| 6 tutorial: | 6 tutorial: |
| 7 id: fetchdata | 7 id: fetchdata |
| 8 next: forms/ | 8 next: forms/ |
| 9 next-title: "Get Input from a Form" | 9 next-title: "Get Input from a Form" |
| 10 prev: polymer-intro/ | 10 prev: polymer-intro/ |
| 11 prev-title: "Define a Custom Element" | 11 prev-title: "Define a Custom Element" |
| 12 --- | 12 --- |
| 13 | 13 |
| 14 {% capture whats_the_point %} | 14 {% capture whats_the_point %} |
| 15 | 15 |
| 16 * Data on the web is often formatted in JSON. | 16 * Data on the web is often formatted in JSON. |
| 17 * JSON is text based and human readable. | 17 * JSON is text based and human readable. |
| 18 * The dart:json library provides support for JSON. | 18 * The dart:convert library provides support for JSON. |
| 19 * Use HttpRequest to dynamically load data. | 19 * Use HttpRequest to dynamically load data. |
| 20 | 20 |
| 21 {% endcapture %} | 21 {% endcapture %} |
| 22 | 22 |
| 23 {% capture sample_links %} | 23 {% capture sample_links %} |
| 24 | 24 |
| 25 <p> | 25 <p> |
| 26 Get the source code for the samples featured in this tutorial:</p> | 26 Get the source code for the samples featured in this tutorial:</p> |
| 27 | 27 |
| 28 <ul> | 28 <ul> |
| (...skipping 20 matching lines...) Expand all Loading... |
| 49 <h3>Get data from a file or server.</h3> | 49 <h3>Get data from a file or server.</h3> |
| 50 </div> | 50 </div> |
| 51 | 51 |
| 52 Web applications often use | 52 Web applications often use |
| 53 <a href="http://www.json.org/" target="_blank">JSON</a> (JavaScript Object Notat
ion) | 53 <a href="http://www.json.org/" target="_blank">JSON</a> (JavaScript Object Notat
ion) |
| 54 to pass data between clients and servers. | 54 to pass data between clients and servers. |
| 55 Data can be _serialized_ into a JSON string, | 55 Data can be _serialized_ into a JSON string, |
| 56 which is then passed between a client and server, | 56 which is then passed between a client and server, |
| 57 and revived as an object at its destination. | 57 and revived as an object at its destination. |
| 58 This tutorial shows you how to use functions in the | 58 This tutorial shows you how to use functions in the |
| 59 <a href="https://api.dartlang.org/dart_json.html" | 59 <a href="https://api.dartlang.org/dart_convert.html" |
| 60 target="_blank">dart:json</a> | 60 target="_blank">dart:convert</a> |
| 61 library to produce and consume JSON data. | 61 library to produce and consume JSON data. |
| 62 Because JSON data is typically loaded dynamically, | 62 Because JSON data is typically loaded dynamically, |
| 63 this tutorial also shows how a web app | 63 this tutorial also shows how a web app |
| 64 can use an HTTP request to get data from an HTTP server. | 64 can use an HTTP request to get data from an HTTP server. |
| 65 For web apps, | 65 For web apps, |
| 66 HTTP requests are served by the browser in which the app is running, | 66 HTTP requests are served by the browser in which the app is running, |
| 67 and thus are subject to the browser's security restrictions. | 67 and thus are subject to the browser's security restrictions. |
| 68 | 68 |
| 69 * [About JSON](#about-json) | 69 * [About JSON](#about-json) |
| 70 * [Serializing data into JSON](#serializing-data-into-json) | 70 * [Serializing data into JSON](#serializing-data-into-json) |
| 71 * [Parsing JSON data](#parsing-json-data) | 71 * [Parsing JSON data](#parsing-json-data) |
| 72 * [About URIs and HTTP requests](#about-uris) | 72 * [About URIs and HTTP requests](#about-uris) |
| 73 * [Using the getString() function to load a file](#using-getString-function) | 73 * [Using the getString() function to load a file](#using-getString-function) |
| 74 * [Using an HttpRequest object to load a file](#making-a-get-request) | 74 * [Using an HttpRequest object to load a file](#making-a-get-request) |
| 75 * [Other resources](#other-resources) | 75 * [Other resources](#other-resources) |
| 76 * [What next?](#what-next) |
| 76 | 77 |
| 77 ##About JSON | 78 ##About JSON |
| 78 | 79 |
| 79 The JSON data format is easy for humans | 80 The JSON data format is easy for humans |
| 80 to write and read because it is lightweight and text based. | 81 to write and read because it is lightweight and text based. |
| 81 With JSON, various data types | 82 With JSON, various data types |
| 82 and simple data structures such as lists and maps | 83 and simple data structures such as lists and maps |
| 83 can be serialized and represented by strings. | 84 can be serialized and represented by strings. |
| 84 | 85 |
| 85 **Try it!** | 86 **Try it!** |
| 86 The app running below, `its_all_about_you`, | 87 The app running below, `its_all_about_you`, |
| 87 displays the JSON string for data of various types. | 88 displays the JSON string for data of various types. |
| 88 Change the values of the input elements | 89 Change the values of the input elements |
| 89 and check out the JSON format for each data type. | 90 and check out the JSON format for each data type. |
| 90 | 91 |
| 91 <iframe class="running-app-frame" | 92 <iframe class="running-app-frame" |
| 92 style="height:500px;width:700px;" | 93 style="height:500px;width:700px;" |
| 93 src="examples/its_all_about_you/out/web/index.html"> | 94 src="examples/its_all_about_you/out/web/index.html"> |
| 94 </iframe> | 95 </iframe> |
| 95 | 96 |
| 96 The complete source code is available on github: | 97 The complete source code is available on github: |
| 97 <a href="https://github.com/dart-lang/dart-tutorials-samples/tree/master/web/fet
chdata/its_all_about_you" | 98 <a href="https://github.com/dart-lang/dart-tutorials-samples/tree/master/web/fet
chdata/its_all_about_you" |
| 98 target="_blank">its_all_about_you</a>. | 99 target="_blank">its_all_about_you</a>. |
| 99 | 100 |
| 100 The dart:json library contains two top-level functions | 101 The dart:convert library contains two convenient functions |
| 101 for working with JSON strings: | 102 for working with JSON strings: |
| 102 | 103 |
| 103 | dart:json function | Description | | 104 | dart:convert function | Description | |
| 104 |---|---| | 105 |---|---| |
| 105 | <a href="https://api.dartlang.org/dart_json.html" target="_blank">parse()</a>
| Builds Dart objects from a string containing JSON data. | | 106 | <a href="https://api.dartlang.org/dart_convert.html" target="_blank">JSON.deco
de()</a> | Builds Dart objects from a string containing JSON data. | |
| 106 | <a href="https://api.dartlang.org/dart_json.html" target="_blank">stringify()<
/a> | Serializes a Dart object into a JSON string. | | 107 | <a href="https://api.dartlang.org/dart_convert.html" target="_blank">JSON.enco
de()</a> | Serializes a Dart object into a JSON string. | |
| 107 {: .table} | 108 {: .table} |
| 108 | 109 |
| 109 The parse() and stringify() functions can handle these Dart types automatically: | 110 To use these functions, |
| 111 you need to import dart:convert into your Dart code: |
| 112 |
| 113 {% highlight dart %} |
| 114 import 'dart:convert'; |
| 115 {% endhighlight %} |
| 116 |
| 117 The JSON.encode() and JSON.decode() functions can handle these Dart types automa
tically: |
| 110 <ul> | 118 <ul> |
| 111 <li> num</li> | 119 <li> num</li> |
| 112 <li> String</li> | 120 <li> String</li> |
| 113 <li> bool</li> | 121 <li> bool</li> |
| 114 <li> null</li> | 122 <li> null</li> |
| 115 <li> List</li> | 123 <li> List</li> |
| 116 <li> Map</li> | 124 <li> Map</li> |
| 117 </ul> | 125 </ul> |
| 118 | 126 |
| 119 Import dart:json using the `as` clause | |
| 120 to give your code clarity | |
| 121 and to avoid naming conflicts. | |
| 122 | |
| 123 {% highlight dart %} | |
| 124 import 'dart:json' as json; | |
| 125 {% endhighlight %} | |
| 126 | |
| 127 ##Serializing data into JSON | 127 ##Serializing data into JSON |
| 128 | 128 |
| 129 Use the stringify() function to serialize an object that supports JSON. | 129 Use the JSON.encode() function to serialize an object that supports JSON. |
| 130 Here's the function from the previous example that | 130 Here's the function, `showJson`, from the its_all_about_you example that |
| 131 converts all of the data to JSON strings. | 131 converts all of the data to JSON strings. |
| 132 | 132 |
| 133  | 133  |
| 134 | 134 |
| 135 Below is the JSON string that results from the code | 135 Below is the JSON string that results from the code |
| 136 using the original values from the its_all_about_you app. | 136 using the original values from the its_all_about_you app. |
| 137 | 137 |
| 138  | 138  |
| 139 | 139 |
| 140 Boolean and numeric values | 140 Boolean and numeric values |
| 141 appear as they would if they were literal values in code, | 141 appear as they would if they were literal values in code, |
| 142 without quotes or other delineating marks. | 142 without quotes or other delineating marks. |
| 143 A boolean value is either `true` or `false`. | 143 A boolean value is either `true` or `false`. |
| 144 A null object is represented with `null`. | 144 A null object is represented with `null`. |
| 145 | 145 |
| 146 Strings are contained within double quotes. | 146 Strings are contained within double quotes. |
| 147 A list is delineated with square brackets; | 147 A list is delineated with square brackets; |
| 148 its items are comma-separated. | 148 its items are comma-separated. |
| 149 The list in this example contains strings. | 149 The list in this example contains strings. |
| 150 A map is delineated with curly brackets; | 150 A map is delineated with curly brackets; |
| 151 it contains comma-separated key/value pairs, | 151 it contains comma-separated key/value pairs, |
| 152 where the key appears first, followed by a colon, | 152 where the key appears first, followed by a colon, |
| 153 followed by the value. | 153 followed by the value. |
| 154 In this example, | 154 In this example, |
| 155 the keys in the map are strings. | 155 the keys in the map are strings. |
| 156 The values in the map vary in type but they are all JSON-parsable. | 156 The values in the map vary in type but they are all JSON-parsable. |
| 157 | 157 |
| 158 ##Parsing JSON data | 158 ##Parsing JSON data |
| 159 | 159 |
| 160 Use the parse() function from the dart:json library to | 160 Use the JSON.decode() function from the dart:convert library to |
| 161 create Dart objects from a JSON string. | 161 create Dart objects from a JSON string. |
| 162 The example above initially populates the values in the form | 162 The its_all_about_you example initially populates the values in the form |
| 163 from this JSON string: | 163 from this JSON string: |
| 164 | 164 |
| 165 {% highlight dart %} | 165 {% highlight dart %} |
| 166 String jsonDataAsString = ''' | 166 String jsonDataAsString = ''' |
| 167 { "favoriteNumber":44, | 167 { "favoriteNumber":44, |
| 168 "valueOfPi":3.141592, | 168 "valueOfPi":3.141592, |
| 169 "chocolate":true, | 169 "chocolate":true, |
| 170 "horrorScope":"virgo", | 170 "horrorScope":"virgo", |
| 171 "favoriteThings":["raindrops", | 171 "favoriteThings":["raindrops", |
| 172 "whiskers", | 172 "whiskers", |
| 173 "mittens"] | 173 "mittens"] |
| 174 } | 174 } |
| 175 '''; | 175 '''; |
| 176 | 176 |
| 177 Map jsonData = json.parse(jsonDataAsString); | 177 Map jsonData = JSON.decode(jsonDataAsString); |
| 178 {% endhighlight %} | 178 {% endhighlight %} |
| 179 | 179 |
| 180 This code calls the parse() function with a properly formatted JSON string. | 180 This code calls the JSON.decode() function with a properly formatted JSON string
. |
| 181 <strong>Note that Dart strings can use either single or double quotes to denote
strings. | 181 <strong>Note that Dart strings can use either single or double quotes to denote
strings. |
| 182 JSON requires double quotes.</strong> | 182 JSON requires double quotes.</strong> |
| 183 | 183 |
| 184 In this example, the full JSON string is hard coded into the Dart code, | 184 In this example, the full JSON string is hard coded into the Dart code, |
| 185 but it could be created by the form itself | 185 but it could be created by the form itself |
| 186 or read from a static file or received from a server. | 186 or read from a static file or received from a server. |
| 187 An example later on this page shows how to dynamically fetch | 187 An example later on this page shows how to dynamically fetch |
| 188 JSON data from a file that is co-located with the code for the app. | 188 JSON data from a file that is co-located with the code for the app. |
| 189 | 189 |
| 190 The parse() function reads the string and | 190 The JSON.decode() function reads the string and |
| 191 builds Dart objects from it. | 191 builds Dart objects from it. |
| 192 In this example, | 192 In this example, |
| 193 the parse() function creates a Map object based on | 193 the JSON.decode() function creates a Map object based on |
| 194 the information in the JSON string. | 194 the information in the JSON string. |
| 195 The Map contains objects of various types | 195 The Map contains objects of various types |
| 196 including an integer, a double, a boolean value, a regular string, | 196 including an integer, a double, a boolean value, a regular string, |
| 197 and a list. | 197 and a list. |
| 198 All of the keys in the map are strings. | 198 All of the keys in the map are strings. |
| 199 | 199 |
| 200 ##About URIs and HTTP requests {#about-uris} | 200 ##About URIs and HTTP requests {#about-uris} |
| 201 | 201 |
| 202 To make an HTTP GET request from within a web app, | 202 To make an HTTP GET request from within a web app, |
| 203 you need to provide a URI (Uniform Resource Identifier) for the resource. | 203 you need to provide a URI (Uniform Resource Identifier) for the resource. |
| (...skipping 211 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 415 | 415 |
| 416  | 416  |
| 417 | 417 |
| 418 The callback function for our example, | 418 The callback function for our example, |
| 419 requestComplete(), | 419 requestComplete(), |
| 420 checks the status code for the request. | 420 checks the status code for the request. |
| 421 If the status code is 200, | 421 If the status code is 200, |
| 422 the file was found and loaded successfully, | 422 the file was found and loaded successfully, |
| 423 The contents of the requested file, `portmanteaux.json`, are | 423 The contents of the requested file, `portmanteaux.json`, are |
| 424 returned in the `responseText` property of an HttpRequest object. | 424 returned in the `responseText` property of an HttpRequest object. |
| 425 Using the `parse()` function from the dart:json library, | 425 Using the `JSON.decode()` function from the dart:convert library, |
| 426 the code easily converts the JSON-formatted list of words | 426 the code easily converts the JSON-formatted list of words |
| 427 to a Dart list of strings, | 427 to a Dart list of strings, |
| 428 creates a new LIElement for each one, | 428 creates a new LIElement for each one, |
| 429 and adds it to the <ul> element on the page. | 429 and adds it to the <ul> element on the page. |
| 430 | 430 |
| 431  | 431  |
| 432 | 432 |
| 433 ###Populating the UI from JSON | 433 ###Populating the UI from JSON |
| 434 | 434 |
| 435 The data file in the portmanteaux example, | 435 The data file in the portmanteaux example, |
| 436 <a href="https://github.com/dart-lang/dart-tutorials-samples/master/web/fetchdat
a/portmanteaux/web/portmanteaux.json" | 436 <a href="https://github.com/dart-lang/dart-tutorials-samples/master/web/fetchdat
a/portmanteaux/web/portmanteaux.json" |
| 437 target="_blank">portmanteaux.json</a>, | 437 target="_blank">portmanteaux.json</a>, |
| 438 contains a JSON-formatted list of strings. | 438 contains a JSON-formatted list of strings. |
| 439 | 439 |
| 440 {% highlight dart %} | 440 {% highlight dart %} |
| 441 [ | 441 [ |
| 442 "portmanteau", "fantabulous", "spork", "smog", | 442 "portmanteau", "fantabulous", "spork", "smog", |
| 443 "spanglish", "gerrymander", "turducken", "stagflation", | 443 "spanglish", "gerrymander", "turducken", "stagflation", |
| 444 "Brangelina", "freeware", "oxbridge", "palimony", | 444 "Brangelina", "freeware", "oxbridge", "palimony", |
| 445 "brunch", "blog", "chortle", "Hassenpfeffer", "Schnitzelbank" | 445 "brunch", "blog", "chortle", "Hassenpfeffer", "Schnitzelbank" |
| 446 ] | 446 ] |
| 447 {% endhighlight %} | 447 {% endhighlight %} |
| 448 | 448 |
| 449 Upon request, the server reads this data from the file | 449 Upon request, the server reads this data from the file |
| 450 and sends it as a single string | 450 and sends it as a single string |
| 451 to the client program. | 451 to the client program. |
| 452 The client program receives the JSON string | 452 The client program receives the JSON string |
| 453 and uses the parse() function from the dart:json library | 453 and uses JSON.decode() |
| 454 to create the String objects specified by the JSON string. | 454 to create the String objects specified by the JSON string. |
| 455 | 455 |
| 456  | 456  |
| 457 | 457 |
| 458 ##Other resources | 458 ##Other resources |
| 459 | 459 |
| 460 Check out Chris Buckett's article, | 460 Check out Chris Buckett's article, |
| 461 <a href="/articles/json-web-service/" | 461 <a href="/articles/json-web-service/" |
| 462 target="_blank">Using Dart with JSON Web Services</a>, | 462 target="_blank">Using Dart with JSON Web Services</a>, |
| 463 for more information and an example with source code for both | 463 for more information and an example with source code for both |
| 464 client and server programs. | 464 client and server programs. |
| 465 | 465 |
| 466 ##What Next? |
| 467 |
| 468 The next tutorial, |
| 469 [Get Input from a Form](/docs/tutorials/forms/), |
| 470 contains a client/server example that |
| 471 shows you how to use a form to get data from the user, |
| 472 and using JSON, send that form to a server, |
| 473 and handle the server's response. |
| 474 |
| 466 {% endcapture %} | 475 {% endcapture %} |
| 467 | 476 |
| 468 {% include tutorial.html %} | 477 {% include tutorial.html %} |
| OLD | NEW |