20260320

そらまめくん(環境省大気汚染物質広域監視システム)のJSONを取得


そらまめくん(環境省大気汚染物質広域監視システム)のJSONを取得

このスクリプトは単体では動作しません

ダウンロードはこちら


【スクリプトエディタで開く】 |

そらまめくんデータ取得.scpt
ソース
001#!/usr/bin/env osascript
002#coding: utf-8
003----+----1----+----2----+-----3----+----4----+----5----+----6----+----7--
004(*
005
006全国の大気汚染状況のAPIを利用して大気の状態を収集します
007https://soramame.env.go.jp/
008
009APIの説明ページ
010https://soramame.env.go.jp/apiManual
011
012前提:期間は直近1ケ月
013
0141:都道府県を選んで
0152:測定局を選んで
0163:JSON取得して ーー>ファイルに保存 まで
017
018グラフ
019https://soramame.env.go.jp/preview/chart/測定局ID/today/測定値/-
020https://soramame.env.go.jp/preview/chart/測定局ID/7day/測定値/-
021一覧
022https://soramame.env.go.jp/preview/table/測定局ID/today/測定値/-
023
024
025この後
026グラフにしたい テーマは花粉症系 続く
027
028
029v0.1 とりあえずデータの取得まで
030
031
032com.cocolog-nifty.quicktimer.icefloe *)
033----+----1----+----2----+-----3----+----4----+----5----+----6----+----7--
034use AppleScript version "2.8"
035use framework "Foundation"
036use framework "AppKit"
037use framework "UniformTypeIdentifiers"
038use scripting additions
039
040property refMe : a reference to current application
041
042########################
043#都道府県コード取得
044set aliasPathToMe to (path to me) as alias
045set strPathToMe to (POSIX path of aliasPathToMe) as text
046set ocidPathToMeStr to refMe's NSString's stringWithString:(strPathToMe)
047set ocidPathToMe to ocidPathToMeStr's stringByStandardizingPath()
048set ocidPathToMeURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidPathToMe) isDirectory:(false)
049set ocidContainerDirPathURL to ocidPathToMeURL's URLByDeletingLastPathComponent()
050set ocidRegJsonFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("json/TDFKN_CD.json") isDirectory:(false)
051#NSDATA
052set ocidOption to (refMe's NSDataReadingMappedIfSafe)
053set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidRegJsonFilePathURL) options:(ocidOption) |error|:(reference)
054set ocidReadData to (item 1 of listResponse)
055#JSON ルートがDICT
056set ocidOption to (refMe's NSJSONReadingJSON5Allowed)
057set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadData) options:(ocidOption) |error|:(reference))
058set ocidJsonDict to (item 1 of listResponse)
059#県名リスト
060set ocidPrefNameArray to ocidJsonDict's valueForKeyPath:("data.prefecture.name")
061#   set ocidPrefCodeArray to ocidJsonDict's valueForKeyPath:("data.prefecture.code")
062#   return ocidPrefCodeArray as list
063#県名とIDのDICT
064set ocidDataDictArray to ocidJsonDict's valueForKeyPath:("data.prefecture")
065set ocidPrefDict to refMe's NSMutableDictionary's alloc()'s init()
066repeat with itemDict in ocidDataDictArray
067   set ocidName to (itemDict's objectForKey:("name"))
068   set ocidID to (itemDict's objectForKey:("code"))
069   (ocidPrefDict's setObject:(ocidID) forKey:(ocidName))
070end repeat
071########################
072#ダイアログ
073set listChooser to ocidPrefNameArray as list
074set strTitle to ("選んでください") as text
075set strPrompt to ("選んでください 複数選択 不可") as text
076set strbuttonOK to ("実行") as text
077set strbuttonCancel to ("キャンセル中止") as text
078try
079   tell application "System Events"
080      activate
081      set listResponse to (choose from list listChooser with title strTitle with prompt strPrompt default items (last item of listChooser) OK button name strbuttonOK cancel button name strbuttonCancel without multiple selections allowed and empty selection allowed) as list
082   end tell
083on error strErrMes number numErrNo
084   log strErrMes & numErrNo
085   return "エラーしました"
086end try
087if listResponse is {} then
088   log "エラー:選択されていません"
089   return return
090else if (first item of listResponse) is false then
091   tell application "System Events" to quit
092   log "エラー:キャンセルしました"
093   return return
094else
095   set strResponse to (first item of listResponse) as text
096end if
097set ocidTDFKN_CD to ocidPrefDict's objectForKey:(strResponse)
098
099########################
100#
101set ocidTsvFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("測定局一覧/測定局一覧.tsv") isDirectory:(false)
102set listReadStrings to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidTsvFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
103set ocidReadStrings to (item 1 of listReadStrings)
104
105set ocidReadArray to ocidReadStrings's componentsSeparatedByString:(linefeed)
106
107############################
108#都道府県DICTを生成
109set ocidStationDict to refMe's NSMutableDictionary's alloc()'s init()
110set ocidChooseDict to refMe's NSMutableDictionary's alloc()'s init()
111set listPrefID to {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47"} as list
112repeat with itemPrefID in listPrefID
113   #
114   set ocidPrefDict to refMe's NSMutableDictionary's alloc()'s init()
115   (ocidStationDict's setObject:(ocidPrefDict) forKey:(itemPrefID))
116   #
117   set ocidNameDict to refMe's NSMutableDictionary's alloc()'s init()
118   (ocidChooseDict's setObject:(ocidNameDict) forKey:(itemPrefID))
119end repeat
120
121
122############################
123#ダイアログ用のDICTを作成
124repeat with itemLine in ocidReadArray
125   #検索用のDICTを先に
126   set ocidLineArray to (itemLine's componentsSeparatedByString:(tab))
127   set ocidPrefID to ocidLineArray's firstObject()
128   set ocidStationID to (ocidLineArray's objectAtIndex:(1))
129   #対象都道府県のDICTを取り出して
130   set ocidAppendDict to (ocidStationDict's objectForKey:(ocidPrefID))
131   (ocidAppendDict's setObject:(ocidLineArray) forKey:(ocidStationID))
132   #後からダイアログ用のDICT
133   set ocidChooseAppendDict to (ocidChooseDict's objectForKey:(ocidPrefID))
134   set ocidStationName to (ocidLineArray's objectAtIndex:(2))
135   
136   (ocidChooseAppendDict's setObject:(ocidStationID) forKey:(ocidStationName))
137end repeat
138
139set ocidPrefNameDict to ocidChooseDict's objectForKey:(ocidTDFKN_CD)
140#return ocidPrefNameDict as record
141set ocidAllKeys to ocidPrefNameDict's allKeys()
142set ocidAllKeys to ocidAllKeys's sortedArrayUsingSelector:("localizedStandardCompare:")
143
144########################
145#ダイアログ
146set listChooser to ocidAllKeys as list
147set strTitle to ("選んでください") as text
148set strPrompt to ("選んでください 複数選択 不可") as text
149set strbuttonOK to ("実行") as text
150set strbuttonCancel to ("キャンセル中止") as text
151try
152   tell application "System Events"
153      activate
154      set listResponse to (choose from list listChooser with title strTitle with prompt strPrompt default items (last item of listChooser) OK button name strbuttonOK cancel button name strbuttonCancel without multiple selections allowed and empty selection allowed) as list
155   end tell
156on error strErrMes number numErrNo
157   log strErrMes & numErrNo
158   return "エラーしました"
159end try
160if listResponse is {} then
161   log "エラー:選択されていません"
162   return return
163else if (first item of listResponse) is false then
164   tell application "System Events" to quit
165   log "エラー:キャンセルしました"
166   return return
167else
168   set strResponse to (first item of listResponse) as text
169end if
170set ocidStarionID to ocidPrefNameDict's objectForKey:(strResponse)
171#
172set ocidPrefDict to ocidStationDict's objectForKey:(ocidTDFKN_CD)
173set ocidStationArray to ocidPrefDict's objectForKey:(ocidStarionID)
174set ocidMeasurement to ocidStationArray's lastObject()
175set ocidMeasurement to (ocidMeasurement's stringByReplacingOccurrencesOfString:("\"") withString:(""))
176
177########################
178#APIURL
179set ocidURLComponents to refMe's NSURLComponents's alloc()'s init()
180ocidURLComponents's setScheme:("https")
181ocidURLComponents's setHost:("soramame.env.go.jp")
182ocidURLComponents's setPath:("/soramame/api/data_search")
183#クエリー
184set ocidQueryItems to refMe's NSMutableArray's alloc()'s init()
185#都道府県ID
186set ocidQuery to refMe's NSURLQueryItem's alloc()'s initWithName:("TDFKN_CD") value:(ocidTDFKN_CD)
187ocidQueryItems's addObject:(ocidQuery)
188#測定局ID
189set ocidQuery to refMe's NSURLQueryItem's alloc()'s initWithName:("SKT_CD") value:(ocidStarionID)
190ocidQueryItems's addObject:(ocidQuery)
191#日付
192set ocidDate to refMe's NSDate's |date|()
193set appFormatter to refMe's NSDateFormatter's alloc()'s init()
194set ocidLocale to refMe's NSLocale's localeWithLocaleIdentifier:("ja_JP_POSIX")
195appFormatter's setLocale:(ocidLocale)
196appFormatter's setDateFormat:("yyyyMM")
197set ocidDateAndTime to appFormatter's stringFromDate:(ocidDate)
198set ocidQuery to refMe's NSURLQueryItem's alloc()'s initWithName:("End_YM") value:(ocidDateAndTime)
199ocidQueryItems's addObject:(ocidQuery)
200#先月
201set appCalendar to refMe's NSCalendar's currentCalendar()
202set ocidDateComponents to refMe's NSDateComponents's alloc()'s init()
203ocidDateComponents's setMonth:(-1)
204set ocidLastMonthDate to appCalendar's dateByAddingComponents:(ocidDateComponents) toDate:(ocidDate) options:(0)
205set ocidLastMonthString to appFormatter's stringFromDate:(ocidLastMonthDate)
206set ocidQuery to refMe's NSURLQueryItem's alloc()'s initWithName:("Start_YM") value:(ocidLastMonthString)
207ocidQueryItems's addObject:(ocidQuery)
208#取得する値
209set ocidQuery to refMe's NSURLQueryItem's alloc()'s initWithName:("REQUEST_DATA") value:(ocidMeasurement)
210ocidQueryItems's addObject:(ocidQuery)
211#クエリーをセットする
212ocidURLComponents's setQueryItems:(ocidQueryItems)
213##URLに戻して テキストにしておく
214set ocidOpenURL to ocidURLComponents's |URL|()
215set strURL to ocidOpenURL's absoluteString() as text
216log return & strURL & return
217########################
218#CDを選択
219set ocidMeasurArray to ocidMeasurement's componentsSeparatedByString:(",")
220log ocidMeasurArray as list
221set recordCDValue to {|SO2|:"二酸化硫黄", |NO|:"一酸化窒素", |NO2|:"二酸化窒素", |NOX|:"窒素酸化物", |CO|:"一酸化炭素", |OX|:"光化学オキシダント", |NMHC|:"非メタン炭化水素", |CH4|:"メタン", |THC|:"全炭化水素", |SPM|:"浮遊粒子状物質", |PM2_5|:"微小粒子状物質", |SP|:"浮遊粉塵", |WD|:"風向", |WS|:"風速", |TEMP|:"気温", |HUM|:"湿度"} as record
222set recordCDValueRev to {|二酸化硫黄|:"SO2", |一酸化窒素|:"NO", |二酸化窒素|:"NO2", |窒素酸化物|:"NOX", |一酸化炭素|:"CO", |光化学オキシダント|:"OX", |非メタン炭化水素|:"NMHC", |メタン|:"CH4", |全炭化水素|:"THC", |浮遊粒子状物質|:"SPM", |微小粒子状物質|:"PM25", |浮遊粉塵|:"SP", |風向|:"WD", |風速|:"WS", |気温|:"TEMP", |湿度|:"HUM"} as record
223
224set ocidCDDict to refMe's NSMutableDictionary's alloc()'s init()
225ocidCDDict's setDictionary:(recordCDValue)
226
227set ocidCDDictRev to refMe's NSMutableDictionary's alloc()'s init()
228ocidCDDictRev's setDictionary:(recordCDValueRev)
229
230set ocidCdArray to refMe's NSMutableArray's alloc()'s init()
231
232repeat with itemMeas in ocidMeasurArray
233   log itemMeas as text
234   set ocidMesName to (ocidCDDict's objectForKey:(itemMeas))
235   (ocidCdArray's addObject:(ocidMesName))
236end repeat
237
238########################
239#ダイアログ
240set listChooser to ocidCdArray as list
241
242if listChooser contains "微小粒子状物質" then
243   set ocidIndexNO to ocidCdArray's indexOfObject:("微小粒子状物質")
244   set numIndex to (ocidIndexNO + 1) as integer
245else
246   set numIndex to (count of listChooser) as integer
247end if
248
249set strTitle to ("選んでください") as text
250set strPrompt to ("選んでください 複数選択 不可") as text
251set strbuttonOK to ("実行") as text
252set strbuttonCancel to ("キャンセル中止") as text
253try
254   tell application "System Events"
255      activate
256      set listResponse to (choose from list listChooser with title strTitle with prompt strPrompt default items (item numIndex of listChooser) OK button name strbuttonOK cancel button name strbuttonCancel without multiple selections allowed and empty selection allowed) as list
257   end tell
258on error strErrMes number numErrNo
259   log strErrMes & numErrNo
260   return "エラーしました"
261end try
262if listResponse is {} then
263   log "エラー:選択されていません"
264   return return
265else if (first item of listResponse) is false then
266   tell application "System Events" to quit
267   log "エラー:キャンセルしました"
268   return return
269else
270   set strResponse to (first item of listResponse) as text
271end if
272set ocidKey to ocidCDDictRev's objectForKey:(strResponse)
273#グラフURL
274set strURL to ("https://soramame.env.go.jp/preview/table/" & ocidStarionID & "/today/" & ocidKey & "/-") as text
275set strURL to ("https://soramame.env.go.jp/preview/chart/" & ocidStarionID & "/today/" & ocidKey & "/-") as text
276set strURL to ("https://soramame.env.go.jp/preview/chart/" & ocidStarionID & "/7day/" & ocidKey & "/-") as text
277set ocidURLString to refMe's NSString's stringWithString:(strURL)
278set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLString)
279#
280set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
281set boolDone to appSharedWorkspace's openURL:(ocidURL)
282
283
284
285########################
286#JSON取得
287set ocidOption to (refMe's NSDataReadingMappedIfSafe)
288set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidOpenURL) options:(ocidOption) |error|:(reference)
289if (item 2 of listResponse) = (missing value) then
290   log "initWithContentsOfURL 正常処理"
291   set ocidReadData to (item 1 of listResponse)
292else if (item 2 of listResponse) ≠ (missing value) then
293   set strErrorNO to (item 2 of listResponse)'s code() as text
294   set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
295   refMe's NSLog("■:" & strErrorNO & strErrorMes)
296   return "initWithContentsOfURL エラーしました" & strErrorNO & strErrorMes
297end if
298#
299set ocidSaveDirPathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("取得データ") isDirectory:(true)
300set appFileManager to refMe's NSFileManager's defaultManager()
301set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
302ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
303set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error|:(reference)
304set strSaveFileName to ("" & ocidStarionID & "_" & strResponse & ".json") as text
305set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false)
306#NSDATA
307set ocidOption to (refMe's NSDataWritingAtomic)
308set listDone to ocidReadData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference)
309
310#JSON ルートがArray
311set ocidOption to (refMe's NSJSONReadingJSON5Allowed)
312set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadData) options:(ocidOption) |error|:(reference))
313set ocidJsonArray to (item 1 of listResponse)
314##ここから JSONをどうするか?考え中
315
316#JSON保存先を開く
317set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
318set boolDone to appSharedWorkspace's openURL:(ocidSaveDirPathURL)
319
320
321return ocidJsonArray as list
AppleScriptで生成しました