Json

[Jedit Ω]ダーク画面用 JSONカラーリング



ダウンロード - json_coloring.plist.zip



202504150732281_570x373

| | コメント (0)

[bash] JQによるJSONの処理

JQによるJSONの処理.bash

サンプルコード

サンプルソース(参考)
行番号ソース
001#!/bin/bash
002#com.cocolog-nifty.quicktimer.icefloe
003#set -x
004#################################################
005###STAT
006STAT_USR=$(/usr/bin/stat -f%Su /dev/console)
007###EXIFTOOL
008#ここは各デバイス毎の設定を反映させて
009PATH_EXIFTOOL="/Users/${STAT_USR}/bin/exiftool/exiftool"
010#一般的にちちらのになると思います
011# PATH_EXIFTOOL="/usr/local/bin/exiftool/exiftool"
012#サンプルの入力画像ファイル
013PATH_IMAGE_FILE="/System/Library/Desktop Pictures/Solid Colors/Black.png"
014#本処理
015JSON_RESPONSE=$("$PATH_EXIFTOOL" -json "$PATH_IMAGE_FILE")
016/bin/echo $JSON_RESPONSE
017#JQ処理
018STR_VALUE=$(/bin/echo "$JSON_RESPONSE" | /usr/bin/jq -r '.[0].ColorType')
019/bin/echo "ColorType: $STR_VALUE"
020STR_VALUE=$(/bin/echo "$JSON_RESPONSE" | /usr/bin/jq -r '.[0].ImageSize')
021/bin/echo "ImageSize: $STR_VALUE"
022STR_VALUE=$(/bin/echo "$JSON_RESPONSE" | /usr/bin/jq -r '.[0].ImageWidth')
023/bin/echo "ImageWidth: $STR_VALUE"
024STR_VALUE=$(/bin/echo "$JSON_RESPONSE" | /usr/bin/jq -r '.[0].ImageHeight')
025/bin/echo "ImageHeight: $STR_VALUE"
026
027#ALLKEYを取得してループで全項目echoする
028/bin/echo "$JSON_RESPONSE" | /usr/bin/jq -r '.[0] | keys[]' | while read ITEM_KEY; do
029  STR_VALUE=$(/bin/echo  "$JSON_RESPONSE" | /usr/bin/jq -r --arg STR_KEY "$ITEM_KEY" '.[0].[$STR_KEY]')
030  /bin/echo "$ITEM_KEY: $STR_VALUE"
031done
032
033exit 0
AppleScriptで生成しました

戻り値 JQによるJSONの処理.bash

サンプルコード

サンプルソース(参考)
行番号ソース
001
002[{ "SourceFile": "/System/Library/Desktop Pictures/Solid Colors/Black.png", "ExifToolVersion": 13.26, "FileName": "Black.png", "Directory": "/System/Library/Desktop Pictures/Solid Colors", "FileSize": "390 bytes", "FileModifyDate": "2025:03:27 20:00:33+09:00", "FileAccessDate": "2025:03:27 20:00:33+09:00", "FileInodeChangeDate": "2025:03:27 20:00:33+09:00", "FilePermissions": "-rw-r--r--", "FileType": "PNG", "FileTypeExtension": "png", "MIMEType": "image/png", "ImageWidth": 128, "ImageHeight": 128, "BitDepth": 8, "ColorType": "RGB with Alpha", "Compression": "Deflate/Inflate", "Filter": "Adaptive", "Interlace": "Noninterlaced", "ImageSize": "128x128", "Megapixels": 0.016 }]
003ColorType: RGB with Alpha
004ImageSize: 128x128
005ImageWidth: 128
006ImageHeight: 128
007BitDepth: 8
008ColorType: RGB with Alpha
009Compression: Deflate/Inflate
010Directory: /System/Library/Desktop Pictures/Solid Colors
011ExifToolVersion: 13.26
012FileAccessDate: 2025:03:27 20:00:33+09:00
013FileInodeChangeDate: 2025:03:27 20:00:33+09:00
014FileModifyDate: 2025:03:27 20:00:33+09:00
015FileName: Black.png
016FilePermissions: -rw-r--r--
017FileSize: 390 bytes
018FileType: PNG
019FileTypeExtension: png
020Filter: Adaptive
021ImageHeight: 128
022ImageSize: 128x128
023ImageWidth: 128
024Interlace: Noninterlaced
025MIMEType: image/png
026Megapixels: 0.016
027SourceFile: /System/Library/Desktop Pictures/Solid Colors/Black.png
AppleScriptで生成しました

| | コメント (0)

[天気予報]www.weatherapi.comのAPIを使って天気情報を取得する(JSON)

www.weatherapi.com天気予報.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*
004www.weatherapi.com のAPIで天気取得
005APIキーが必要です
006 com.cocolog-nifty.quicktimer.icefloe*)
007----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
008use AppleScript version "2.8"
009use framework "Foundation"
010use framework "AppKit"
011use framework "UniformTypeIdentifiers"
012use scripting additions
013
014property refMe : a reference to current application
015
016
017set strApiKey to ("XXXXXXXXXXXXXXXXX") as text
018
019####################
020#設定項目
021set strURL to "https://api.weatherapi.com/v1/current.json"
022set strSetURL to ("" & strURL & "?key=" & strApiKey & "&q=tokyo&aqi=yes") as text
023
024####################
025#URL
026set ocidUrlStr to refMe's NSString's stringWithString:(strSetURL)
027set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidUrlStr)
028
029####################
030#出力用テキスト
031set ocidOutputString to refMe's NSMutableString's alloc()'s init()
032
033####################
034#NSDATA
035set ocidOption to (refMe's NSDataReadingMappedIfSafe)
036set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error| :(reference)
037if (item 2 of listResponse) = (missing value) then
038  log "initWithContentsOfURL 正常処理"
039  set ocidReadJsonData to (item 1 of listResponse)
040else if (item 2 of listResponse) (missing value) then
041  set strErrorNO to (item 2 of listResponse)'s code() as text
042  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
043  refMe's NSLog("■:" & strErrorNO & strErrorMes)
044  return "initWithContentsOfURL エラーしました" & strErrorNO & strErrorMes
045end if
046####################
047#JSON ルートがDICT
048set ocidOption to (refMe's NSJSONReadingJSON5Allowed)
049set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadJsonData) options:(ocidOption) |error| :(reference))
050if (item 2 of listResponse) = (missing value) then
051  log "JSONObjectWithData 正常処理"
052  set ocidJsonDict to (item 1 of listResponse)
053else if (item 2 of listResponse) (missing value) then
054  set strErrorNO to (item 2 of listResponse)'s code() as text
055  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
056  refMe's NSLog("■:" & strErrorNO & strErrorMes)
057  return "JSONObjectWithData エラーしました" & strErrorNO & strErrorMes
058end if
059log ocidJsonDict's allKeys() as list
060####################
061#centers
062set ocidCentersDict to ocidJsonDict's objectForKey:("current")
063#
064set ocidText to (ocidCentersDict's valueForKeyPath:("condition.text"))
065set strIcon to (ocidCentersDict's valueForKeyPath:("condition.icon")) as text
066set strIcon to ("https:" & strIcon & "") as text
067ocidOutputString's appendString:("<h1>東京: ")
068ocidOutputString's appendString:(ocidText)
069ocidOutputString's appendString:("</h1>")
070ocidOutputString's appendString:("<p><img src=\"")
071ocidOutputString's appendString:(strIcon)
072ocidOutputString's appendString:("\"></p>")
073#
074set ocidTemp to (ocidCentersDict's valueForKeyPath:("temp_c"))'s stringValue()
075set ocidMb to (ocidCentersDict's valueForKeyPath:("pressure_mb"))'s stringValue()
076ocidOutputString's appendString:("<p>気温: ")
077ocidOutputString's appendString:(ocidTemp)
078ocidOutputString's appendString:("</p>")
079ocidOutputString's appendString:("<p>気圧: ")
080ocidOutputString's appendString:(ocidMb)
081ocidOutputString's appendString:("</p>")
082#
083
084####################
085#保存先
086set appFileManager to refMe's NSFileManager's defaultManager()
087set ocidTempDirURL to appFileManager's temporaryDirectory()
088set ocidUUID to refMe's NSUUID's alloc()'s init()
089set ocidUUIDString to ocidUUID's UUIDString
090set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:(true)
091#
092set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
093ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
094set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error| :(reference)
095if (item 1 of listDone) is false then
096  set strErrorNO to (item 2 of listDone)'s code() as text
097  set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
098  refMe's NSLog("■:" & strErrorNO & strErrorMes)
099  log "createDirectoryAtURL エラーしました" & strErrorNO & strErrorMes
100  return false
101end if
102###パス
103set strFileName to "weatherapi.html" as text
104set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
105set listDone to ocidOutputString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference)
106if (item 1 of listDone) is true then
107  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
108  set boolDone to appSharedWorkspace's openURL:(ocidSaveFilePathURL)
109
110else if (item 1 of listDone) is false then
111  log (item 2 of listDone)'s localizedDescription() as text
112  return "保存に失敗しました"
113end if
114
115return ocidOutputString as text
116
117
118
119
120
121to doGetDateNo(strDateFormat)
122  ####日付情報の取得
123  set ocidDate to current application's NSDate's |date|()
124  ###日付のフォーマットを定義
125  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
126  ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
127  ocidNSDateFormatter's setDateFormat:strDateFormat
128  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
129  set strDateAndTime to ocidDateAndTime as text
130  return strDateAndTime
131end doGetDateNo
132
AppleScriptで生成しました

| | コメント (0)

[bash]Teamsの最新バージョンを取得する

fwlinkは2種類あるけど
リダイレクト先は同じ
#旧Classic版のURLだけど今は最新版にリダイレクトされる
https://go.microsoft.com/fwlink/?linkid=869428
#最新版
https://go.microsoft.com/fwlink/?linkid=2249065
#リダイレクト先
https://statics.teams.cdn.office.net/production-osx/enterprise/webview2/lkg/MicrosoftTeams.pkg
ホストは3つにわかれている
若干役割が違うようにするために分けたんだろうけど
実際は中身は同じ場合もある

バージョン 25060.203.3471.5023の場合
https://statics.teams.cdn.office.net/production-osx/25060.203.3471.5023/MicrosoftTeams.pkg
https://staticsint.teams.cdn.office.net/production-osx/25060.203.3471.5023/MicrosoftTeams.pkg
https://installer.teams.static.microsoft/production-osx/25060.203.3471.5023/MicrosoftTeams.pkg
この3つのURL
中身は同じ


Teamsの最新バージョンを取得する.bash

サンプルコード

サンプルソース(参考)
行番号ソース
001#!/bin/bash
002#com.cocolog-nifty.quicktimer.icefloe
003#set -x
004#export PATH=/usr/bin:/bin:/usr/sbin:/sbin
005# MicrosoftTeams-msinternal を参考にしました
006# https://github.com/ItzLevvie/MicrosoftTeams-msinternal
007#################################################
008
009STR_URL="https://config.teams.microsoft.com/config/v1/MicrosoftTeams/28_1.0.0.0?environment=prod&audienceGroup=general&teamsRing=general&id=3a7cf1d3-06fa-4ead-bf45-a6286ff2620a&tenantId=72f988bf-86f1-41af-91ab-2d7cd011db47&agent=TeamsBuilds"
010
011STR_VERSION=$(/usr/bin/nscurl "$STR_URL" | /usr/bin/jq -r '.BuildSettings.WebView2.macOS.latestVersion')
012/bin/echo "$STR_VERSION"
013
014STR_PKG_URL=$(/usr/bin/nscurl "$STR_URL" | /usr/bin/jq -r '.BuildSettings.WebView2.macOS.buildLink')
015/bin/echo "$STR_PKG_URL"
016
017
018exit 0
AppleScriptで生成しました

| | コメント (0)

[appleScript]Teamsの最新バージョンを取得する


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

Teamsの最新バージョンを取得する.scpt
ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*
004MicrosoftTeams-msinternal を参考にしました
005https://github.com/ItzLevvie/MicrosoftTeams-msinternal
006
007v1.1 テキスト出力するようにした
008com.cocolog-nifty.quicktimer.icefloe *)
009----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
010use AppleScript version "2.8"
011use framework "Foundation"
012use framework "AppKit"
013use scripting additions
014
015property refMe : a reference to current application
016
017#28 or 50MacOS
018set strPlatformId to ("28") as text
019#dev prod life gcc
020set strEnvironment to ("prod") as text
021#ring0 ring3_9 general general_gcc 
022set strRing to ("general") as text
023set strObjectId to ("3a7cf1d3-06fa-4ead-bf45-a6286ff2620a") as text
024set strTenantId to ("72f988bf-86f1-41af-91ab-2d7cd011db47") as text
025
026
027set strURL to ("https://config.teams.microsoft.com/config/v1/MicrosoftTeams/" & strPlatformId & "_1.0.0.0?environment=" & strEnvironment & "&audienceGroup=" & strRing & "&teamsRing=" & strRing & "&agent=TeamsBuilds") as text
028
029set strURL to ("https://config.teams.microsoft.com/config/v1/MicrosoftTeams/" & strPlatformId & "_1.0.0.0?environment=" & strEnvironment & "&audienceGroup=" & strRing & "&teamsRing=" & strRing & "&id=" & strObjectId & "&tenantId=" & strTenantId & "&agent=TeamsBuilds") as text
030
031log "\r" & strURL & "\r"
032
033set ocidURLString to refMe's NSString's stringWithString:(strURL)
034set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLString)
035
036
037##NSDATA
038set ocidOption to (refMe's NSDataReadingMappedIfSafe)
039set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
040if (item 2 of listResponse) = (missing value) then
041   set ocidReadJsonData to (item 1 of listResponse)
042else if (item 2 of listResponse) ≠ (missing value) then
043   set strErrorNO to (item 2 of listResponse)'s code() as text
044   set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
045   refMe's NSLog("■" & strErrorNO & strErrorMes)
046   return "initWithContentsOfURL エラーしました" & strErrorNO & strErrorMes
047end if
048
049
050####################
051#JSON ルートがDICT
052set ocidOption to (refMe's NSJSONReadingJSON5Allowed)
053set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadJsonData) options:(ocidOption) |error|:(reference))
054if (item 2 of listResponse) = (missing value) then
055   set ocidJsonDict to (item 1 of listResponse)
056else if (item 2 of listResponse) ≠ (missing value) then
057   set strErrorNO to (item 2 of listResponse)'s code() as text
058   set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
059   refMe's NSLog("■" & strErrorNO & strErrorMes)
060   return "JSONObjectWithData エラーしました" & strErrorNO & strErrorMes
061end if
062
063####################
064#
065set ocidBuildDict to ocidJsonDict's objectForKey:("BuildSettings")
066set ocidWebView2Dict to ocidBuildDict's objectForKey:("WebView2")
067set ocidmacOSDict to ocidWebView2Dict's objectForKey:("macOS")
068set ocidVersion to ocidmacOSDict's valueForKey:("latestVersion")
069set ocidPkgURL to ocidmacOSDict's valueForKey:("buildLink")
070log ocidVersion as text
071log ocidPkgURL as text
072
073set strVersion to (ocidJsonDict's valueForKeyPath:("BuildSettings.WebView2.macOS.latestVersion")) as text
074set strPkgURL to (ocidJsonDict's valueForKeyPath:("BuildSettings.WebView2.macOS.buildLink")) as text
075
076log strVersion
077log strPkgURL
078
079####################
080#出力用
081set ocidOutPutString to refMe's NSMutableString's alloc()'s init()
082ocidOutPutString's appendString:("\n")
083
084set strFwlink to ("https://go.microsoft.com/fwlink/?linkid=869428") as text
085ocidOutPutString's appendString:(strFwlink)
086ocidOutPutString's appendString:("\n")
087set strFwlink to ("https://go.microsoft.com/fwlink/?linkid=2249065") as text
088ocidOutPutString's appendString:(strFwlink)
089ocidOutPutString's appendString:("\n")
090
091set strEnterpriseURL to ("https://statics.teams.cdn.office.net/production-osx/enterprise/webview2/lkg/MicrosoftTeams.pkg") as text
092ocidOutPutString's appendString:(strEnterpriseURL)
093ocidOutPutString's appendString:("\n")
094
095set strEnterpriseURL to ("https://statics.teams.cdn.office.net/production-osx/" & strVersion & "/MicrosoftTeams.pkg") as text
096ocidOutPutString's appendString:(strEnterpriseURL)
097ocidOutPutString's appendString:("\n")
098set strEnterpriseURL to ("https://staticsint.teams.cdn.office.net/production-osx/" & strVersion & "/MicrosoftTeams.pkg") as text
099ocidOutPutString's appendString:(strEnterpriseURL)
100ocidOutPutString's appendString:("\n")
101set strEnterpriseURL to ("https://installer.teams.static.microsoft/production-osx/" & strVersion & "/MicrosoftTeams.pkg") as text
102ocidOutPutString's appendString:(strEnterpriseURL)
103ocidOutPutString's appendString:("\n")
104
105####################
106#保存
107set appFileManager to refMe's NSFileManager's defaultManager()
108set ocidTempDirURL to appFileManager's temporaryDirectory()
109set ocidUUID to refMe's NSUUID's alloc()'s init()
110set ocidUUIDString to ocidUUID's UUIDString
111set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:(true)
112set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
113ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
114set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error|:(reference)
115###パス
116set strFileName to "index.txt" as text
117set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
118set listDone to ocidOutPutString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
119#開く
120set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
121set boolDone to appSharedWorkspace's openURL:(ocidSaveFilePathURL)
122
123
AppleScriptで生成しました

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

001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*
004MicrosoftTeams-msinternal を参考にしました
005https://github.com/ItzLevvie/MicrosoftTeams-msinternal
006
007com.cocolog-nifty.quicktimer.icefloe *)
008----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
009use AppleScript version "2.8"
010use framework "Foundation"
011use framework "AppKit"
012use scripting additions
013
014property refMe : a reference to current application
015
016#28 or 50MacOS
017set strPlatformId to ("28") as text
018#dev prod life gcc
019set strEnvironment to ("prod") as text
020#ring0 ring3_9 general general_gcc 
021set strRing to ("general") as text
022set strObjectId to ("3a7cf1d3-06fa-4ead-bf45-a6286ff2620a") as text
023set strTenantId to ("72f988bf-86f1-41af-91ab-2d7cd011db47") as text
024
025
026set strURL to ("https://config.teams.microsoft.com/config/v1/MicrosoftTeams/" & strPlatformId & "_1.0.0.0?environment=" & strEnvironment & "&audienceGroup=" & strRing & "&teamsRing=" & strRing & "&agent=TeamsBuilds") as text
027
028set strURL to ("https://config.teams.microsoft.com/config/v1/MicrosoftTeams/" & strPlatformId & "_1.0.0.0?environment=" & strEnvironment & "&audienceGroup=" & strRing & "&teamsRing=" & strRing & "&id=" & strObjectId & "&tenantId=" & strTenantId & "&agent=TeamsBuilds") as text
029
030
031set ocidURLString to refMe's NSString's stringWithString:(strURL)
032set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLString)
033
034
035##NSDATA
036set ocidOption to (refMe's NSDataReadingMappedIfSafe)
037set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
038if (item 2 of listResponse) = (missing value) then
039   set ocidReadJsonData to (item 1 of listResponse)
040else if (item 2 of listResponse) ≠ (missing value) then
041   set strErrorNO to (item 2 of listResponse)'s code() as text
042   set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
043   refMe's NSLog("■" & strErrorNO & strErrorMes)
044   return "initWithContentsOfURL エラーしました" & strErrorNO & strErrorMes
045end if
046
047
048####################
049#JSON ルートがDICT
050set ocidOption to (refMe's NSJSONReadingJSON5Allowed)
051set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadJsonData) options:(ocidOption) |error|:(reference))
052if (item 2 of listResponse) = (missing value) then
053   set ocidJsonDict to (item 1 of listResponse)
054else if (item 2 of listResponse) ≠ (missing value) then
055   set strErrorNO to (item 2 of listResponse)'s code() as text
056   set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
057   refMe's NSLog("■" & strErrorNO & strErrorMes)
058   return "JSONObjectWithData エラーしました" & strErrorNO & strErrorMes
059end if
060
061####################
062#
063set ocidBuildDict to ocidJsonDict's objectForKey:("BuildSettings")
064set ocidWebView2Dict to ocidBuildDict's objectForKey:("WebView2")
065set ocidmacOSDict to ocidWebView2Dict's objectForKey:("macOS")
066set ocidVersion to ocidmacOSDict's valueForKey:("latestVersion")
067set ocidPkgURL to ocidmacOSDict's valueForKey:("buildLink")
068log ocidVersion as text
069log ocidPkgURL as text
070
071set strVersion to (ocidJsonDict's valueForKeyPath:("BuildSettings.WebView2.macOS.latestVersion")) as text
072set strPkgURL to (ocidJsonDict's valueForKeyPath:("BuildSettings.WebView2.macOS.buildLink")) as text
073
074log strVersion
075log strPkgURL

| | コメント (0)

[AppleScript]気象庁のJSON取得してテキスト出力する

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

001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*
004気象庁のJSON取得
005Jsonの取得と解析は難しくないが
006『海がない気象台』『観測所にはURLがない』とかがあることをお忘れなく
007V2 色々直した
008 com.cocolog-nifty.quicktimer.icefloe*)
009----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
010use AppleScript version "2.8"
011use framework "Foundation"
012use framework "AppKit"
013use framework "UniformTypeIdentifiers"
014use scripting additions
015
016property refMe : a reference to current application
017
018####################
019#設定項目
020set strAreaUrl to "https://www.jma.go.jp/bosai/common/const/area.json"
021
022
023####################
024#出力用テキスト
025set ocidOutPutArray to refMe's NSMutableArray's alloc()'s init()
026
027####################
028#URL
029set ocidAreaUrlStr to refMe's NSString's stringWithString:(strAreaUrl)
030set ocidAreaURL to refMe's NSURL's alloc()'s initWithString:(ocidAreaUrlStr)
031
032####################
033#NSDATA
034set ocidOption to (refMe's NSDataReadingMappedIfSafe)
035set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidAreaURL) options:(ocidOption) |error|:(reference)
036if (item 2 of listResponse) = (missing value) then
037   log "initWithContentsOfURL 正常処理"
038   set ocidReadJsonData to (item 1 of listResponse)
039else if (item 2 of listResponse) ≠ (missing value) then
040   set strErrorNO to (item 2 of listResponse)'s code() as text
041   set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
042   refMe's NSLog("■" & strErrorNO & strErrorMes)
043   return "initWithContentsOfURL エラーしました" & strErrorNO & strErrorMes
044end if
045####################
046#JSON ルートがDICT
047set ocidOption to (refMe's NSJSONReadingJSON5Allowed)
048set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadJsonData) options:(ocidOption) |error|:(reference))
049if (item 2 of listResponse) = (missing value) then
050   log "JSONObjectWithData 正常処理"
051   set ocidJsonDict to (item 1 of listResponse)
052else if (item 2 of listResponse) ≠ (missing value) then
053   set strErrorNO to (item 2 of listResponse)'s code() as text
054   set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
055   refMe's NSLog("■" & strErrorNO & strErrorMes)
056   return "JSONObjectWithData エラーしました" & strErrorNO & strErrorMes
057end if
058####################
059#centers 
060set ocidCentersDict to ocidJsonDict's objectForKey:("centers")
061set ocidCentersArray to ocidCentersDict's allKeys()
062#ソート
063set ocidCentersArray to ocidCentersArray's sortedArrayUsingSelector:("compare:")
064#ダイアログ用の地方気象台名リスト
065set listCenterName to {} as list
066#逆引きDICT
067set ocidReverseCenterDict to refMe's NSMutableDictionary's alloc()'s init()
068repeat with itemKey in ocidCentersArray
069   set ocidCenter to (ocidCentersDict's valueForKey:(itemKey))
070   set strCenterName to (ocidCenter's valueForKey:("officeName")) as text
071   copy strCenterName to end of listCenterName
072   (ocidReverseCenterDict's setValue:(itemKey) forKey:(strCenterName))
073end repeat
074
075####################
076#ダイアログ
077set strName to (name of current application) as text
078if strName is "osascript" then
079   tell application "SystemUIServer" to activate
080else
081   tell current application to activate
082end if
083try
084   tell application "SystemUIServer"
085      activate
086      set valueResponse to (choose from list listCenterName with title "選んでください" with prompt "地方気象台を選んでください" default items (item 3 of listCenterName) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed)
087   end tell
088on error
089   tell application "SystemUIServer" to quit
090   log "Error choose from list"
091   return false
092end try
093tell application "SystemUIServer" to quit
094if (class of valueResponse) is boolean then
095   log "Error キャンセルしました"
096   error "ユーザによってキャンセルされました。" number -128
097else if (class of valueResponse) is list then
098   if valueResponse is {} then
099      log "Error 何も選んでいません"
100      return false
101   else
102      set strResponse to (item 1 of valueResponse) as text
103   end if
104end if
105set ocidOutPutStrint to refMe's NSString's stringWithString:("天気予報: Center: " & strResponse & "\n")
106(ocidOutPutArray's addObject:(ocidOutPutStrint))
107####################
108#逆引き辞書からセンター番号を取得
109set ocidCenterNo to ocidReverseCenterDict's valueForKey:(strResponse)
110#センター番号からOffice情報を取得
111set ocidOfficeDict to (ocidCentersDict's objectForKey:(ocidCenterNo))
112#Office情報 DICTから気象台番号を取得
113set ocidOfficeNoArray to (ocidOfficeDict's objectForKey:("children"))
114set ocidOfficeNoArray to ocidOfficeNoArray's sortedArrayUsingSelector:("compare:")
115
116####################
117#offices
118set ocidOfficesDict to ocidJsonDict's objectForKey:("offices")
119set ocidOfficesArray to ocidOfficesDict's allKeys()
120#測候所はURLがないので除外
121set appPredicate to refMe's NSPredicate's predicateWithFormat_("SELF CONTAINS %@", "測候所")
122set ocidOfficesArrayRev to ocidOfficesArray's filteredArrayUsingPredicate:(appPredicate)
123set ocidOfficesArray to ocidOfficesArrayRev's sortedArrayUsingSelector:("compare:")
124#ダイアログ用の気象台名リスト
125set listOfficesName to {} as list
126#逆引きDICT
127set ocidReverseOfficesDict to refMe's NSMutableDictionary's alloc()'s init()
128repeat with itemKey in ocidOfficeNoArray
129   set ocidOffice to (ocidOfficesDict's valueForKey:(itemKey))
130   set strOfficeName to (ocidOffice's valueForKey:("officeName")) as text
131   if strOfficeName does not contain "測候所" then
132      copy strOfficeName to end of listOfficesName
133      (ocidReverseOfficesDict's setValue:(itemKey) forKey:(strOfficeName))
134   end if
135end repeat
136
137
138####################
139#ダイアログ
140set strName to (name of current application) as text
141if strName is "osascript" then
142   tell application "SystemUIServer" to activate
143else
144   tell current application to activate
145end if
146try
147   tell application "SystemUIServer"
148      activate
149      set valueResponse to (choose from list listOfficesName with title "選んでください" with prompt "気象台を選んでください" default items (last item of listOfficesName) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed)
150   end tell
151on error
152   tell application "SystemUIServer" to quit
153   log "Error choose from list"
154   return false
155end try
156tell application "SystemUIServer" to quit
157if (class of valueResponse) is boolean then
158   log "Error キャンセルしました"
159   error "ユーザによってキャンセルされました。" number -128
160else if (class of valueResponse) is list then
161   if valueResponse is {} then
162      log "Error 何も選んでいません"
163      return false
164   else
165      set strResponse to (item 1 of valueResponse) as text
166   end if
167end if
168set ocidOutPutStrint to refMe's NSString's stringWithString:("Office: " & strResponse & " 発表\n")
169(ocidOutPutArray's addObject:(ocidOutPutStrint))
170
171#######################
172#本処理 天気予報jSON取得
173set ocidOfficeNo to ocidReverseOfficesDict's valueForKey:(strResponse)
174set strOfficeNo to ocidOfficeNo as text
175#日付
176set strDate to doGetDateNo("yyyyMMddhhmmss") as text
177###URL整形
178set strURL to ("https://www.jma.go.jp/bosai/forecast/data/forecast/" & strOfficeNo & ".json?__time__=" & strDate & "") as text
179log "\r" & strURL & "\r"
180####################
181#URL
182set ocidUrlStr to refMe's NSString's stringWithString:(strURL)
183set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidUrlStr)
184
185####################
186#NSDATA
187set ocidOption to (refMe's NSDataReadingMappedIfSafe)
188set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
189if (item 2 of listResponse) = (missing value) then
190   log "initWithContentsOfURL 正常処理"
191   set ocidReadJsonData to (item 1 of listResponse)
192else if (item 2 of listResponse) ≠ (missing value) then
193   set strErrorNO to (item 2 of listResponse)'s code() as text
194   set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
195   refMe's NSLog("■" & strErrorNO & strErrorMes)
196   return "initWithContentsOfURL エラーしました" & strErrorNO & strErrorMes
197end if
198####################
199#JSON ルートがArray
200set ocidOption to (refMe's NSJSONReadingJSON5Allowed)
201set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadJsonData) options:(ocidOption) |error|:(reference))
202if (item 2 of listResponse) = (missing value) then
203   log "JSONObjectWithData 正常処理"
204   set ocidJsonArray to (item 1 of listResponse)
205else if (item 2 of listResponse) ≠ (missing value) then
206   set strErrorNO to (item 2 of listResponse)'s code() as text
207   set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
208   refMe's NSLog("■" & strErrorNO & strErrorMes)
209   return "JSONObjectWithData エラーしました" & strErrorNO & strErrorMes
210end if
211####################
212#天気予報辞書 天気予報 と 習慣天気予報
213set ocidDailyDict to ocidJsonArray's firstObject()
214set ocidWeeklyDict to ocidJsonArray's firstObject()
215
216####################
217#各項目取得
218set ocidTimeSeriesArray to ocidDailyDict's objectForKey:("timeSeries")
219set ocidWeathers to ocidTimeSeriesArray's firstObject()
220set ocidRainPops to ocidTimeSeriesArray's objectAtIndex:(1)
221set ocidTemps to ocidTimeSeriesArray's lastObject()
222
223####################
224#天気予報
225set strOutPutStrint to ("") as text
226set ocidAreaArray to ocidWeathers's objectForKey:("areas")
227repeat with itemArea in ocidAreaArray
228   set strAreaName to ((itemArea's objectForKey:("area"))'s valueForKey:("name")) as text
229   set ocidWeathersArray to (itemArea's objectForKey:("weathers"))
230   set ocidWindsArray to (itemArea's objectForKey:("winds"))
231   set ocidWavesArray to (itemArea's objectForKey:("waves"))
232   set numCntWavesArray to ocidWavesArray's |count|()
233   repeat with itemNo from 0 to (numCntWavesArray - 1) by 1
234      set strOutPutStrint to ("" & strOutPutStrint & strAreaName & "地方\n") as text
235      if itemNo = 0 then
236         set strOutPutStrint to ("" & strOutPutStrint & "今日の天気: ") as text
237      else if itemNo = 1 then
238         set strOutPutStrint to ("" & strOutPutStrint & "明日の天気: ") as text
239      else if itemNo = 2 then
240         set strOutPutStrint to ("" & strOutPutStrint & "明後日の天気: ") as text
241      end if
242      set strSetString to (ocidWeathersArray's objectAtIndex:(itemNo))
243      set strOutPutStrint to ("" & strOutPutStrint & strSetString & "\n\t風: ") as text
244      set strSetString to (ocidWindsArray's objectAtIndex:(itemNo))
245      set strOutPutStrint to ("" & strOutPutStrint & strSetString & "\n") as text
246      if ocidWavesArray ≠ (missing value) then
247         set strSetString to (ocidWavesArray's objectAtIndex:(itemNo))
248         set strOutPutStrint to ("" & strOutPutStrint & "\t波: " & strSetString & "\n") as text
249      end if
250   end repeat
251   set strOutPutStrint to ("" & strOutPutStrint & "\n") as text
252end repeat
253set ocidOutPutStrint to refMe's NSString's stringWithString:(strOutPutStrint)
254ocidOutPutArray's addObject:(ocidOutPutStrint)
255####################
256#降雨確率
257set strOutPutStrint to ("降水確率(6時間毎)\n") as text
258set ocidAreaArray to ocidRainPops's objectForKey:("areas")
259repeat with itemArea in ocidAreaArray
260   set ocidAreaName to ((itemArea's objectForKey:("area"))'s valueForKey:("name"))
261   set strOutPutStrint to ("" & strOutPutStrint & ocidAreaName & "地域: ") as text
262   set ocidPopsString to ((itemArea's objectForKey:("pops"))'s componentsJoinedByString:("→"))
263   set strOutPutStrint to ("" & strOutPutStrint & ocidPopsString & "\n") as text
264end repeat
265set ocidOutPutStrint to refMe's NSString's stringWithString:(strOutPutStrint)
266ocidOutPutArray's addObject:(ocidOutPutStrint)
267####################
268#気温
269set strOutPutStrint to ("気温(12時間毎)\n") as text
270set ocidAreaArray to ocidTemps's objectForKey:("areas")
271repeat with itemArea in ocidAreaArray
272   set ocidAreaName to ((itemArea's objectForKey:("area"))'s valueForKey:("name"))
273   set strOutPutStrint to ("" & strOutPutStrint & ocidAreaName & "地域: ") as text
274   set ocidTempString to ((itemArea's objectForKey:("temps"))'s componentsJoinedByString:("→"))
275   set strOutPutStrint to ("" & strOutPutStrint & ocidTempString & "\n") as text
276end repeat
277set ocidOutPutStrint to refMe's NSString's stringWithString:(strOutPutStrint)
278(ocidOutPutArray's addObject:(ocidOutPutStrint))
279
280####################
281#出力用テキスト
282set ocidJoinText to ocidOutPutArray's componentsJoinedByString:("\n")
283#保存先
284set appFileManager to refMe's NSFileManager's defaultManager()
285set ocidTempDirURL to appFileManager's temporaryDirectory()
286set ocidUUID to refMe's NSUUID's alloc()'s init()
287set ocidUUIDString to ocidUUID's UUIDString
288set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:(true)
289#
290set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
291ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
292set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error|:(reference)
293if (item 1 of listDone) is false then
294   set strErrorNO to (item 2 of listDone)'s code() as text
295   set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
296   refMe's NSLog("■" & strErrorNO & strErrorMes)
297   log "createDirectoryAtURL エラーしました" & strErrorNO & strErrorMes
298   return false
299end if
300###パス
301set strFileName to "jma.txt" as text
302set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
303
304set listDone to ocidJoinText's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
305if (item 1 of listDone) is true then
306   set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
307   set boolDone to appSharedWorkspace's openURL:(ocidSaveFilePathURL)
308   
309else if (item 1 of listDone) is false then
310   log (item 2 of listDone)'s localizedDescription() as text
311   return "保存に失敗しました"
312end if
313
314
315return ocidJoinText as text
316
317
318
319
320
321to doGetDateNo(strDateFormat)
322   ####日付情報の取得
323   set ocidDate to current application's NSDate's |date|()
324   ###日付のフォーマットを定義
325   set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
326   ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
327   ocidNSDateFormatter's setDateFormat:strDateFormat
328   set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
329   set strDateAndTime to ocidDateAndTime as text
330   return strDateAndTime
331end doGetDateNo
332

| | コメント (0)

[JSON]JSONの編集基本的な流れ

JOSNの編集.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011property refMe : a reference to current application
012set appFileManager to refMe's NSFileManager's defaultManager()
013###################################
014#パス
015set strFilePath to "~/Desktop/Jsonまでのパス.json" as text
016set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
017set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
018set ocidJsonFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
019
020###################################
021##  JSONをバックアップ
022#拡張子とって
023set ocidBaseFilePathURL to ocidJsonFilePathURL's URLByDeletingPathExtension()
024set strDateNo to doGetDateNo("yyyyMMdd")
025#日付入りにして
026set strSetValue to ("" & strDateNo & ".json")
027set ocidBakupJsonFilePathURL to ocidBaseFilePathURL's URLByAppendingPathExtension:(strSetValue)
028#バックアップ
029set listDone to (appFileManager's copyItemAtURL:(ocidJsonFilePathURL) toURL:(ocidBakupJsonFilePathURL) |error| :(reference))
030if (item 1 of listDone) is true then
031  log "copyItemAtURL 正常処理"
032else if (item 2 of listDone) (missing value) then
033  set strErrorNO to (item 2 of listDone)'s code() as text
034  set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
035  refMe's NSLog("■:" & strErrorNO & strErrorMes)
036  log "エラーしました" & strErrorNO & strErrorMes
037  doExecAlert("copyItemAtURL でエラーしました")
038end if
039
040###################################
041## SDATAに読み込む
042set ocidOption to (refMe's NSDataReadingMappedIfSafe)
043set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidJsonFilePathURL) options:(ocidOption) |error| :(reference)
044if (item 2 of listResponse) = (missing value) then
045  log "initWithContentsOfURL 正常処理"
046  set ocidReadData to (item 1 of listResponse)
047else if (item 2 of listResponse) (missing value) then
048  set strErrorNO to (item 2 of listResponse)'s code() as text
049  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
050  refMe's NSLog("■:" & strErrorNO & strErrorMes)
051  log "initWithContentsOfURL エラーしました" & strErrorNO & strErrorMes
052  doExecAlert("initWithContentsOfURL でエラーしました")
053end if
054###################################
055## JSONObjectWithData
056set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadData) options:(refMe's NSJSONReadingMutableContainers) |error| :(reference))
057if (item 2 of listResponse) = (missing value) then
058  log "JSONObjectWithData 正常処理"
059set ocidJsonData to item 1 of listResponse
060else if (item 2 of listResponse) (missing value) then
061  set strErrorNO to (item 2 of listResponse)'s code() as text
062  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
063  refMe's NSLog("■:" & strErrorNO & strErrorMes)
064  log "JSONObjectWithData エラーしました" & strErrorNO & strErrorMes
065  doExecAlert("JSONObjectWithData")
066end if
067
068
069###################################
070## ROOT構造がArrayか?DICTか?の判定
071#確認できたら不要
072set boolArrayM to ocidJsonData's isKindOfClass:(refMe's NSMutableArray's class)
073set boolArray to ocidJsonData's isKindOfClass:(refMe's NSArray's class)
074set boolDictM to ocidJsonData's isKindOfClass:(refMe's NSMutableDictionary's class)
075set boolDict to ocidJsonData's isKindOfClass:(refMe's NSDictionary's class)
076#
077if boolArrayM is true then
078  log "root ARRAY構造です 可変"
079  set ocidJsonArray to ocidJsonData
080else if boolArray is true then
081  log "root ARRAY構造です フローズンなので mutableCopy"
082  set ocidJsonArray to ocidJsonData's mutableCopy()
083else if boolDictM is true then
084  log "root DICT構造です 可変"
085  set ocidJsonDict to ocidJsonData
086else if boolDict is true then
087  log "root DICT構造です  フローズンなので mutableCopy"
088  set ocidJsonDict to ocidJsonData's mutableCopy()
089end if
090
091###################################
092# ここで各種処理する
093
094
095###################################
096#ROOTの構造を確認できたら不要
097if boolArrayM is true then
098  set ocidPlistData to ocidJsonArray
099else if boolArray is true then
100  set ocidPlistData to ocidJsonArray
101else if boolDictM is true then
102  set ocidPlistData to ocidJsonDict
103else if boolDict is true then
104  set ocidPlistData to ocidJsonDict
105end if
106
107###################################
108# dataWithJSONObject でNSDATAにして
109set listResponse to (refMe's NSJSONSerialization's dataWithJSONObject:(ocidPlistData) options:(refMe's NSJSONReadingJSON5Allowed) |error| :(reference))
110if (item 2 of listResponse) is (missing value) then
111  set ocidJsonData to (item 1 of listResponse)
112  log "dataWithJSONObject 正常終了"
113else
114  set strErrorNO to (item 2 of listResponse)'s code() as text
115  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
116  refMe's NSLog("■:" & strErrorNO & strErrorMes)
117  doExecAlert("dataWithJSONObject でエラーしました")
118end if
119
120###################################
121# 保存
122set ocidOption to (refMe's NSDataWritingAtomic)
123set listDone to ocidJsonData's writeToURL:(ocidJsonFilePathURL) options:(ocidOption) |error| :(reference)
124if (item 1 of listDone) is true then
125  log "writeToURL 正常終了"
126else if (item 1 of listDone) is false then
127  set strErrorNO to (item 2 of listDone)'s code() as text
128  set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
129  refMe's NSLog("■:" & strErrorNO & strErrorMes)
130  doExecAlert("writeToURL 失敗しました")
131  return "writeToURL 失敗しました"
132end if
133
134
135##########################
136#【K】エラーアラート
137to doExecAlert(argMessageText)
138  #ダイアログを前面に出す
139  set strName to (name of current application) as text
140  if strName is "osascript" then
141    tell application "Finder" to activate
142  else
143    tell current application to activate
144  end if
145  try
146    set recordResponse to (display alert argMessageText buttons {"終了", "再実行"} default button "終了" cancel button "終了" as informational giving up after 5) as record
147  on error
148    log "エラーしました"
149    return "キャンセルしました。"
150  end try
151  if true is equal to (gave up of recordResponse) then
152    return "時間切れです。"
153  end if
154  set strBottonName to (button returned of recordResponse) as text
155  if "再実行" is equal to (strBottonName) then
156    tell application "Finder"
157      set aliasPathToMe to (path to me) as alias
158    end tell
159    run script aliasPathToMe with parameters "再実行"
160    return
161  else if "終了" is equal to (strBottonName) then
162    return "終了を確認しました。"
163  else if "中断" is equal to (strBottonName) then
164    return "中断"
165  end if
166end doExecAlert
167
168##########################
169#日付の取得
170to doGetDateNo(strDateFormat)
171  ####日付情報の取得
172  set ocidDate to current application's NSDate's |date|()
173  ###日付のフォーマットを定義
174  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
175  ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
176  ocidNSDateFormatter's setDateFormat:strDateFormat
177  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
178  set strDateAndTime to ocidDateAndTime as text
179  return strDateAndTime
180end doGetDateNo
AppleScriptで生成しました

|

[Json]Jsonファイルをplistに変換する(保存先指定できるようにした)

JSON2PLIT.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*  com.cocolog-nifty.quicktimer.icefloe
004Json2Plist
005JSON形式のテキストをPLISTに変換します
006v2 jsonのrootの構造がArrayなのか?DICTなのか?の判定を入れた
007保存先をデスクトップに変更した
008保存先を選べるようにした
009*)
010#
011----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
012##自分環境がos12なので2.8にしているだけです
013use AppleScript version "2.8"
014use framework "Foundation"
015use framework "AppKit"
016use scripting additions
017
018property refMe : a reference to current application
019
020
021####ダイアログで使うデフォルトロケーション
022tell application "Finder"
023  set aliasDefaultLocation to (path to desktop folder from user domain) as alias
024end tell
025####UTIリスト
026set listUTI to {"public.json", "com.netscape.javascript-source"}
027####ダイアログを出す
028set aliasFilePath to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
029
030set strFilePath to (POSIX path of aliasFilePath) as text
031##########################################
032###【1】ドキュメントのパスをNSString
033set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
034set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
035set ocidFilePathURL to refMe's NSURL's fileURLWithPath:(ocidFilePath)
036
037##########################################
038### 【2】ファイルをNSDATAとして読み込み
039(*   NSDataReadingOptions
040(*1*)log refMe's NSDataReadingMappedIfSafe as integer
041(*2*)log refMe's NSDataReadingUncached as integer
042(*8*)log refMe's NSDataReadingMappedAlways as integer
043*)
044set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(refMe's NSDataReadingMappedIfSafe) |error| :(reference)
045set coidReadData to item 1 of listReadData
046
047##########################################
048### 【3】JSON初期化
049(*  NSJSONReadingOptions
050(*1*)log refMe's NSJSONReadingMutableContainers as integer
051(*2*)log refMe's NSJSONReadingMutableLeaves as integer
052(*4*)log refMe's NSJSONReadingFragmentsAllowed as integer
053(*8*)log refMe's NSJSONReadingJSON5Allowed as integer
054(*16*)log refMe's NSJSONReadingTopLevelDictionaryAssumed as integer
055*)
056set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(coidReadData) options:(refMe's NSJSONReadingMutableContainers) |error| :(reference))
057set ocidJsonData to item 1 of listJSONSerialization
058#ROOT構造がArrayか?DICTか?の判定
059set ocidJsonClass to ocidJsonData's className()
060set boolContainArray to ocidJsonClass's containsString:("NSArray")
061
062##########################################
063####【4】レコードに格納
064#実際はここで色々処理したりデータ取得したりします
065
066#最後に出力用に名前を変えて(まぁ必要ないんだけどなんとなく)
067if boolContainArray is false then
068  set ocidJsonPlist to refMe's NSDictionary's alloc()'s initWithDictionary:(ocidJsonData)
069else if boolContainArray is true then
070  set ocidJsonPlist to refMe's NSArray's alloc()'s initWithArray:(ocidJsonData)
071end if
072
073##########################################
074####【5】PLISTに変換 (optionは 0-2 Immutable /MutableContainers /MutableContainersAndLeaves)
075set ocidFromat to refMe's NSPropertyListXMLFormat_v1_0
076set listPlistEditDataArray to refMe's NSPropertyListSerialization's dataWithPropertyList:(ocidJsonData) format:(ocidFromat) options:0  |error| :(reference)
077set ocidPlistEditData to item 1 of listPlistEditDataArray
078
079##########################################
080####【6】保存
081#デスクトップにする
082set appFileManager to refMe's NSFileManager's defaultManager()
083set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
084set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
085set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
086set ocidFileName to ocidFilePathURL's lastPathComponent()
087set ocidFileExtension to ocidFilePathURL's pathExtension()
088#
089set ocidPrefixName to ocidFileName's stringByDeletingPathExtension()
090set strPrefixName to ocidPrefixName as text
091set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
092set strFileExtension to "plist"
093set strDefaultName to (strPrefixName & "." & strFileExtension) as text
094set strPromptText to "名前を決めてください"
095set strMesText to "名前を決めてください"
096
097#ダイアログ
098set strName to (name of current application) as text
099if strName is "osascript" then
100  tell application "Finder" to activate
101else
102  tell current application to activate
103end if
104set aliasSaveFilePath to (choose file name strMesText default location aliasDefaultLocation default name strDefaultName with prompt strPromptText) as «class furl»
105#
106set strSaveFilePath to(POSIX path of aliasSaveFilePath) as text
107set ocidSaveFilePath to refMe's NSString's stringWithString:(strSaveFilePath)
108set ocidSaveFilePathURL to refMe's NSURL's fileURLWithPath:(ocidSaveFilePath)
109set strFileExtensionName to ocidSaveFilePathURL's pathExtension() as text
110if strFileExtensionName is not strFileExtension then
111  set ocidSaveFilePathURL to ocidSaveFilePathURL's URLByAppendingPathExtension:strFileExtension
112end if
113
114
115
116###保存
117set boolWritetoUrlArray to ocidPlistEditData's writeToURL:(ocidSaveFilePathURL) options:0  |error| :(reference)
118
119return "処理終了"
AppleScriptで生成しました

|

[JSON] JSON 2 PLIST 少し修正


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*  com.cocolog-nifty.quicktimer.icefloe
004Json2Plist
005JSON形式のテキストをPLISTに変換します
006v2 jsonのrootの構造がArrayなのか?DICTなのか?の判定を入れた
007*)
008#
009----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
010##自分環境がos12なので2.8にしているだけです
011use AppleScript version "2.8"
012use framework "Foundation"
013use scripting additions
014
015property refMe : a reference to current application
016
017
018####ダイアログで使うデフォルトロケーション
019tell application "Finder"
020  set aliasDefaultLocation to (path to desktop folder from user domain) as alias
021end tell
022####UTIリスト
023set listUTI to {"public.json", "com.netscape.javascript-source"}
024####ダイアログを出す
025set aliasFilePath to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
026
027set strFilePath to (POSIX path of aliasFilePath) as text
028##########################################
029###【1】ドキュメントのパスをNSString
030set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
031set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
032set ocidFilePathURL to refMe's NSURL's fileURLWithPath:(ocidFilePath)
033
034##########################################
035### 【2】ファイルをNSDATAとして読み込み
036(*   NSDataReadingOptions
037(*1*)log refMe's NSDataReadingMappedIfSafe as integer
038(*2*)log refMe's NSDataReadingUncached as integer
039(*8*)log refMe's NSDataReadingMappedAlways as integer
040*)
041set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(refMe's NSDataReadingMappedIfSafe) |error| :(reference)
042set coidReadData to item 1 of listReadData
043
044##########################################
045### 【3】JSON初期化
046(*  NSJSONReadingOptions
047(*1*)log refMe's NSJSONReadingMutableContainers as integer
048(*2*)log refMe's NSJSONReadingMutableLeaves as integer
049(*4*)log refMe's NSJSONReadingFragmentsAllowed as integer
050(*8*)log refMe's NSJSONReadingJSON5Allowed as integer
051(*16*)log refMe's NSJSONReadingTopLevelDictionaryAssumed as integer
052*)
053set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(coidReadData) options:(refMe's NSJSONReadingMutableContainers) |error| :(reference))
054set ocidJsonData to item 1 of listJSONSerialization
055#ROOT構造がArrayか?DICTか?の判定
056set ocidJsonClass to ocidJsonData's className()'s stringValue()
057set boolContainArray to ocidJsonClass's containsString:("NSArray")
058
059##########################################
060####【4】レコードに格納
061#実際はここで色々処理したりデータ取得したりします
062
063#最後に出力用に名前を変えて(まぁ必要ないんだけどなんとなく)
064if boolContainArray is false then
065  set ocidJsonPlist to refMe's NSDictionary's alloc()'s initWithDictionary:(ocidJsonData)
066else if boolContainArray is true then
067  set ocidJsonPlist to refMe's NSArray's alloc()'s initWithArray:(ocidJsonData)
068end if
069
070##########################################
071####【5】PLISTに変換 (optionは 0-2 Immutable /MutableContainers /MutableContainersAndLeaves)
072set ocidFromat to refMe's NSPropertyListXMLFormat_v1_0
073set listPlistEditDataArray to refMe's NSPropertyListSerialization's dataWithPropertyList:(ocidJsonData) format:(ocidFromat) options:0  |error| :(reference)
074set ocidPlistEditData to item 1 of listPlistEditDataArray
075
076##########################################
077####【6】保存
078###保存先パスをURLを生成して
079set ocidBaseFileURL to ocidFilePathURL's URLByDeletingPathExtension()
080set ocidSaveFilePathURL to ocidBaseFileURL's URLByAppendingPathExtension:"plist"
081###保存
082set boolWritetoUrlArray to ocidPlistEditData's writeToURL:(ocidSaveFilePathURL) options:0  |error| :(reference)
083
084return "処理終了"
AppleScriptで生成しました

|

[Json]ROOTがDict形式のJSONの操作



ダウンロード - jsonbasic.zip




AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "AppKit"
009use framework "UniformTypeIdentifiers"
010use scripting additions
011property refMe : a reference to current application
012property ocidChosenFilePathURL : missing value
013
014
015##################
016#ファイル選択ダイアログ
017on appChooseFile:(ocidArgDirPathURL)
018  set ocidOpenPanel to refMe's NSOpenPanel's openPanel()
019  ocidOpenPanel's setDirectoryURL:(ocidArgDirPathURL)
020  ocidOpenPanel's setCanChooseFiles:(true)
021  ocidOpenPanel's setCanChooseDirectories:(false)
022  ocidOpenPanel's setAllowsMultipleSelection:(false)
023  ocidOpenPanel's setAccessoryViewDisclosed:(true)
024  ocidOpenPanel's setTitle:"ファイルを選んでください"
025  ocidOpenPanel's setPrompt:"実行"
026  ocidOpenPanel's setMessage:"JSONファイルを選んでください"
027  ocidOpenPanel's setShowsTagField:(true)
028  ocidOpenPanel's setResolvesAliases:(false)
029  ocidOpenPanel's setShowsHiddenFiles:(true)
030  ocidOpenPanel's setExtensionHidden:(false)
031  ocidOpenPanel's setCanCreateDirectories:(true)
032  ocidOpenPanel's setCanDownloadUbiquitousContents:(true)
033  ocidOpenPanel's setCanResolveUbiquitousConflicts:(true)
034  ocidOpenPanel's setCanSelectHiddenExtension:(true)
035  ocidOpenPanel's setTreatsFilePackagesAsDirectories:(true)
036  #対象のUTIを限定する
037  set listUTI to {"public.json"} as list
038  set ocidUTIarray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
039  repeat with itemUTI in listUTI
040    set ocidItemUTType to (refMe's UTType's typeWithIdentifier:(itemUTI))
041    (ocidUTIarray's addObject:(ocidItemUTType))
042  end repeat
043  #UTTypeを限定項目としてセット
044  ocidOpenPanel's setAllowedContentTypes:(ocidUTIarray)
045  #実行
046  set returnCode to ocidOpenPanel's runModal()
047  #キャンセルをmissing value
048  if returnCode = (refMe's NSModalResponseCancel) then
049    log "キャンセル"
050    error number -128
051  else if returnCode = (refMe's NSModalResponseOK) then
052    log "OK"
053    set my ocidChosenFilePathURL to ocidOpenPanel's |URL|()
054    return
055  end if
056  
057end appChooseFile:
058##################
059# path to me
060set aliasPathToMe to (path to me) as alias
061set strPathToMe to (POSIX path of aliasPathToMe) as text
062set ocidPathToMeStr to refMe's NSString's stringWithString:(strPathToMe)
063set ocidPathToMe to ocidPathToMeStr's stringByStandardizingPath()
064set ocidPathToMeURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidPathToMe) isDirectory:(false)
065set ocidContainerDirPathURL to ocidPathToMeURL's URLByDeletingLastPathComponent()
066
067##################
068#ダイアログ実行
069my performSelectorOnMainThread:("appChooseFile:") withObject:(ocidContainerDirPathURL) waitUntilDone:(true)
070#ダイアログの戻り値
071set ocidFilePathURL to ocidChosenFilePathURL
072
073##################
074# ここから本処理
075##################
076#保存先
077set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
078set ocidSaveFilePathURL to ocidBaseFilePathURL's URLByAppendingPathExtension:("plist")
079
080##################
081#NSDATA
082set ocidOption to (refMe's NSDataReadingMappedIfSafe)
083set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(ocidOption) |error| :(reference)
084set ocidReadData to (item 1 of listResponse)
085
086##################
087#JSONシリアル
088set appJsonSerial to (refMe's NSJSONSerialization)
089set ocidOption to (refMe's NSJSONReadingMutableContainers)
090set listResponse to appJsonSerial's JSONObjectWithData:(ocidReadData) options:(ocidOption) |error| :(reference)
091set ocidJsonDict to (item 1 of listResponse)
092
093##################
094#本処理
095# レコード=辞書構造の子構造に
096# リスト=配列構造のデータ
097# 操作するならここ
098set ocidFontsArray to ocidJsonDict's objectForKey:("Fonts")
099repeat with itemArray in ocidFontsArray
100  log (itemArray's valueForKey:("f")) as text
101end repeat
102
103##################
104#PLIST
105set ocidFormat to (refMe's NSPropertyListXMLFormat_v1_0)
106set listResponse to refMe's NSPropertyListSerialization's dataWithPropertyList:(ocidJsonDict) format:(ocidFormat) options:0  |error| :(reference)
107set ocidSaveData to (item 1 of listResponse)
108
109##################
110#保存
111set ocidOption to (refMe's NSDataWritingAtomic)
112set listDone to ocidSaveData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error| :(reference)
AppleScriptで生成しました

|

より以前の記事一覧

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat 2024 Acrobat AddOn Acrobat Annotation Acrobat AppleScript Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat GentechAI Acrobat JS Acrobat JS Word Search Acrobat Maintenance Acrobat Manifest Acrobat Menu Acrobat Merge Acrobat Open Acrobat PDFPage Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Print Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat Registered Products Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat URL List Mac Acrobat URL List Windows Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin ConfigCode Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin NetWork Admin Permission Admin Pkg Admin Power Management Admin Printer Admin Printer Basic Admin Printer Custompapers Admin SetUp Admin SMB Admin softwareupdate Admin Support Admin System Information Admin TCC Admin Tools Admin Umask Admin Users Admin Volumes Admin XProtect Adobe Adobe AUSST Adobe Bridge Adobe Documents Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager Adobe Sap Code AppKit Apple AppleScript AppleScript Duplicate AppleScript entire contents AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Video Applications AppStore Archive Archive Keka Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome Chromedriver CIImage CityCode CloudStorage Color Color NSColor Color NSColorList com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Desktop Position Device Diff Disk do shell script Dock Dock Launchpad DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData exiftool ffmpeg File File Name Finder Finder Window Firefox Folder FolderAction Font List FontCollections Fonts Fonts Asset_Font Fonts ATS Fonts Emoji Fonts Maintenance Fonts Morisawa Fonts Python Fonts Variable Foxit GIF github Guide HTML Icon Icon Assets.car Illustrator Image Events ImageOptim Input Dictionary iPhone iWork Javascript Jedit Ω Json Label Language Link locationd lsappinfo m3u8 Mail Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Microsoft Fonts Microsoft Office Microsoft Office Link Microsoft OneDrive Microsoft Teams Mouse Music Node Notes NSArray NSArray Sort NSAttributedString NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSGraphicsContext Crop NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSet NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSUbiquitous NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth PDF PDF Image2PDF PDF MakePDF PDF nUP PDF Pymupdf PDF Pypdf PDFContext PDFDisplayBox PDFImageRep PDFKit PDFKit Annotation PDFKit AnnotationWidget PDFKit DocumentPermissions PDFKit OCR PDFKit Outline PDFKit Start PDFPage PDFPage Rotation PDFView perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript PowerShell prefPane Preview Python Python eyed3 Python pip QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver Script Editor Script Menu SF Symbols character id SF Symbols Entity Shortcuts Shortcuts Events sips Skype Slack Sound Spotlight sqlite StandardAdditions StationSearch Subtitles LRC Subtitles SRT Subtitles VTT Swift swiftDialog System Events System Settings TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code VMware Fusion Wacom Weather webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML LSSharedFileList sfl2 XML LSSharedFileList sfl3 XML objectsForXQuery XML OPML XML Plist XML Plist System Events XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube Zero Padding zoom