2020年3月2日月曜日

Decoding JSON by using new Dictionary Blocks

This article demonstrates the use of new blocks called Dictionaries [1] in MIT App Inventor. These blocks were announced in the releases nb181c and nb182 (February 18, 2020) and are mainly used for encoding and decoding JSON files.

By the way, I previously developed a JSON Decoding Extension. Examples of its use are shown below:
Another example using JSON Decoding Extension

In the following, I use the new Dictionaries to decode JSON file for the same example. This app displays the weather forecast using OpenWeather [2]. Here, I show the weather forecast for Sapporo City in Japan every 3 hours up to 5 days ahead. Fig.1 shows an example of JSON text output from OpenWeather. Some parts are folded in the figure, but if all are expanded, there are 1,341 lines.


Fig.2 shows an application that takes all the values for tags surrounded by a red frame in this JSON text and displays them on the smartphone. Namely, values for the city name, time, temperature, and weather are displayed. To use OpenWeather in this application, you need to obtain your own API Key.


This application uses Dictionaries blocks to decode JSON text. First, get the city name "Sapporo" as shown in Fig.3. The JSON text obtained from OpenWeather is processed by a web block, and the result is made into a list structure. (global jsonL). Next, the city name is obtained by the "get value at key path" method of the Dictionary block.


Next, to extract all the weather forecasts (time, temperature, description) every 3 hours, use the procedure shown in Fig.4. First, traverse the array that is the value of the "list" tag by specifying "walk all at level". The resulting list (global subList) is used in the subsequent blocks. For example, to get all the temperatures and put the result into a list structure, use the "list by walking key path" method. At this time, the element given as an argument is a list of (walk all at level, main, temp). Here, the order of the list elements is important. It is necessary to carefully specify the order while looking closely at the hierarchical structure of the JSON file. I think Fig.5 will help you understand it.




As a result of the above tests, I found that the new "Dictionaries blocks" can efficiently decode JSON files, similar to the "JSON Decoding Extension" described above.

References
[1] MIT App Inventor Dictionary Blocks
http://ai2.appinventor.mit.edu/reference/blocks/dictionaries.html
[2] OpenWeaterMap API guide
https://openweathermap.org/guide

2 件のコメント:

  1. hi, nice tutorial, however I'm struggling to get it working - would you be please able to share full "code"

    返信削除
    返信
    1. Thank you for your interest in this article. However, I have given enough information to reproduce this: almost complete code and detailed instructions. Therefore, I hope you read this article in detail again and apply it to your own application.

      削除