AppleScript Json

[Json]PlistをJsonに変換する(NSTaggedDate対策入り)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
日付データNSTaggedDateをstringに置換してから
PLISTデータをJSON形式にします
com.cocolog-nifty.quicktimer.icefloe
*)
#
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application


####ダイアログで使うデフォルトロケーション
tell application "Finder"
  set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
####UTIリスト
set listUTI to {"com.apple.property-list", "public.xml"}
####ダイアログを出す
set aliasFilePath to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias

set strFilePath to (POSIX path of aliasFilePath) as text
set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set ocidFilePathURL to refMe's NSURL's fileURLWithPath:(ocidFilePath)
set ocidFileName to ocidFilePathURL's lastPathComponent()
##########################################
###【1】テンポラリディレクトリとパス
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTempDirURL to appFileManager's temporaryDirectory()
set ocidUUID to refMe's NSUUID's alloc()'s init()
set ocidUUIDString to ocidUUID's UUIDString
set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
if (item 1 of listDone) is true then
  #テンポラリファイル
  set ocidTmpFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidFileName) isDirectory:false
log "【1】正常終了"
else if (item 1 of listDone) is false then
log (item 2 of listDone)'s localizedDescription() as text
return "【1】失敗しました"
end if


##########################################
### 【2】PLISTファイルをNSDATAとして読み込み
(* NSDataReadingOptions
(*1*)log refMe's NSDataReadingMappedIfSafe as integer
(*2*)log refMe's NSDataReadingUncached as integer
(*8*)log refMe's NSDataReadingMappedAlways as integer
*)
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(refMe's NSDataReadingMappedIfSafe) |error|:(reference)
if (item 2 of listReadData) is (missing value) then
  set coidReadData to (item 1 of listReadData)
log " 【2】正常終了"
else
log (item 2 of listReadData)'s localizedDescription() as text
return " 【2】失敗しました"
end if


##########################################
####【3】PLISTに変換 (optionは 0-2 Immutable /MutableContainers /MutableContainersAndLeaves)
set ocidXmlPlist to refMe's NSPropertyListXMLFormat_v1_0
set ocidPlistSerial to refMe's NSPropertyListSerialization
set ocidOption to refMe's NSPropertyListMutableContainersAndLeaves
set listPlistDict to ocidPlistSerial's propertyListWithData:(coidReadData) options:(ocidOption) format:(ocidXmlPlist) |error|:(reference)
if (item 2 of listPlistDict) is (missing value) then
  set ocidPlistDict to (item 1 of listPlistDict)
log "【3】正常終了"
else
log (item 2 of listPlistDict)'s localizedDescription() as text
return "【3】失敗しました"
end if


##########################################
####【4】テンポラリファイルを保存
set ocidOption to (refMe's NSDataWritingWithoutOverwriting)
set listDone to ocidPlistDict's writeToURL:(ocidTmpFilePathURL) |error|:(reference)
if (item 1 of listDone) is true then
log "【4】正常終了"
else if (item 1 of listDone) is false then
log (item 2 of listDone)'s localizedDescription() as text
return "【4】失敗しました"
end if
##########################################
####【5】テンポラリのPLISTの『フォーマット』を変更
set listReadString to refMe's NSMutableString's alloc()'s initWithContentsOfURL:(ocidTmpFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
if (item 2 of listReadString) is (missing value) then
  set ocidReadString to (item 1 of listReadString)
log "【5-1】正常終了"
else
log (item 2 of listReadString)'s localizedDescription() as text
return "【5-1】失敗しました"
end if
##置換
set ocidSaveString to ocidReadString's stringByReplacingOccurrencesOfString:("<date>") withString:("<string>")
set ocidSaveString to ocidSaveString's stringByReplacingOccurrencesOfString:("</date>") withString:("</string>")
set ocidSaveString to ocidSaveString's stringByReplacingOccurrencesOfString:("<data>") withString:("<string>")
set ocidSaveString to ocidSaveString's stringByReplacingOccurrencesOfString:("</data>") withString:("</string>")
##上書き保存
set listDone to ocidSaveString's writeToURL:(ocidTmpFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
if (item 1 of listDone) is true then
log "【5-2】正常終了"
else if (item 1 of listDone) is false then
log (item 2 of listDone)'s localizedDescription() as text
return "【5-2】失敗しました"
end if
##########################################
### 【6】PLISTファイルをNSDATAとして読み込み
set listReadTmpData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidTmpFilePathURL) options:(refMe's NSDataReadingMappedIfSafe) |error|:(reference)
if (item 2 of listReadTmpData) is (missing value) then
  set ocidReadTmpData to (item 1 of listReadTmpData)
log "【6】正常終了"
else
log (item 2 of listReadTmpData)'s localizedDescription() as text
return "【6】失敗しました"
end if
##########################################
####【7】PLISTに変換 (optionは 0-2 Immutable /MutableContainers /MutableContainersAndLeaves)
set ocidXmlPlist to refMe's NSPropertyListXMLFormat_v1_0
set ocidPlistSerial to refMe's NSPropertyListSerialization
set ocidOption to refMe's NSPropertyListMutableContainersAndLeaves
set listPlistDict to ocidPlistSerial's propertyListWithData:(ocidReadTmpData) options:(ocidOption) format:(ocidXmlPlist) |error|:(reference)
if (item 2 of listPlistDict) is (missing value) then
  set ocidPlistDict to (item 1 of listPlistDict)
log "【7】正常終了"
else
log (item 2 of listPlistDict)'s localizedDescription() as text
return "【7】失敗しました"
end if

##########################################
### 【8】JSON初期化
(* NSJSONReadingOptions
(*1*)log refMe's NSJSONReadingMutableContainers as integer
(*2*)log refMe's NSJSONReadingMutableLeaves as integer
(*4*)log refMe's NSJSONReadingFragmentsAllowed as integer
(*8*)log refMe's NSJSONReadingJSON5Allowed as integer
(*16*)log refMe's NSJSONReadingTopLevelDictionaryAssumed as integer
*)
set listJSONSerialization to (refMe's NSJSONSerialization's dataWithJSONObject:(ocidPlistDict) options:(refMe's NSJSONReadingJSON5Allowed) |error|:(reference))
if (item 2 of listJSONSerialization) is (missing value) then
  set ocidJsonData to (item 1 of listJSONSerialization)
log "【8】正常終了"
else
log (item 2 of listJSONSerialization)'s localizedDescription() as text
return "【8】失敗しました"
end if


##########################################
####【9】保存
###保存先パスをURLを生成して
set ocidBaseFileURL to ocidFilePathURL's URLByDeletingPathExtension()
set ocidSaveFilePathURL to ocidBaseFileURL's URLByAppendingPathExtension:"json"
###保存
set ocidOption to (refMe's NSDataWritingAtomic)
set listDone to ocidJsonData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference)
if (item 1 of listDone) is true then
log "【9】正常終了"
else if (item 1 of listDone) is false then
log (item 2 of listDone)'s localizedDescription() as text
return "【9】失敗しました"
end if

return "処理終了"

|

[Json] JSONの操作 自分まとめ

JSON関連カテゴリー
https://quicktimer.cocolog-nifty.com/icefloe/cat76049735/index.html



1:ApplescriptAsで処理する
2:ApplescriptOcで処理する
3:JSON Helperを使う
4:コマンドラインツールを利用する


A:URLから処理する
B:ファイルにして処理する


1:ApplescriptAsで処理する
A:リスト化して処理する
[Json]List化して処理する
B:レコード化して処理する
[Json] Record化して処理する


2:ApplescriptOcで処理する
[JSON]JSONの取扱 その1(rootがDict形式の場合)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-7ac684.html
[JSON]JSONの取扱 その2(rootがArray形式の場合)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-0ed292.html


3:JSON Helperを使う
[Json]JSON Helper
https://quicktimer.cocolog-nifty.com/icefloe/2022/04/post-8f8bb6.html
[JOSN]気象庁の天気予報(JSON Helper変換)
https://quicktimer.cocolog-nifty.com/icefloe/2022/04/post-6825eb.html


A:URLから処理する
[Json]祝祭日の取得
https://quicktimer.cocolog-nifty.com/icefloe/2022/11/post-37464d.html
B:ファイルにして処理する
[exiftool]JSONデータをPLISTに変換する
https://quicktimer.cocolog-nifty.com/icefloe/2022/10/post-1f6a98.html
[JOSN]気象庁の天気予報(Plist変換)
https://quicktimer.cocolog-nifty.com/icefloe/2022/04/post-79c9d8.html


4:コマンドラインツールを利用する
/usr/bin/plutil jsonをplistに変換する
https://quicktimer.cocolog-nifty.com/icefloe/2022/04/post-79c9d8.html
jq Command-line JSON processor
https://github.com/jqlang/jq


5:ツール類
Visual Studio Code
https://code.visualstudio.com/Download
Visual Studio Code機能拡張
https://marketplace.visualstudio.com/search?term=json
CotEditor
https://coteditor.com

|

[ip.guide]IPアドレス取得(IPアドレスからの位置情報付き)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions
property refMe : a reference to current application

##############################
#####本処理
##############################
### 【1】JSONのURL
set ocidComponents to refMe's NSURLComponents's alloc()'s init()
ocidComponents's setScheme:("https")
ocidComponents's setHost:("ip.guide")
set ocidURL to ocidComponents's |URL|
### 【2】URLの内容JSONをNSdataに格納
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
set ocidReadData to (item 1 of listReadData)
### 【3】NSPropertyListSerializationしてレコードに
set ocidOption to (refMe's NSJSONReadingMutableContainers)
set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadData) options:(ocidOption) |error|:(reference))
set ocidPlistDict to item 1 of listJSONSerialization
##
set strIP to (ocidPlistDict's valueForKey:("ip")) as text
set ocidLocationDict to (ocidPlistDict's valueForKey:("location"))
set strLat to ocidLocationDict's valueForKey:("latitude")
set strLong to ocidLocationDict's valueForKey:("longitude")

(*
###MapURL
set strMapURL to ("https://maps.apple.com/?ll=" & strLat & "," & strLong & "") as text
###NabiTime
set strMapURL to ("https://www.navitime.co.jp/maps/aroundResult?lat=" & strLat & "&lon=" & strLong & "&type=station&radius=2000") as text
###
set strMapURL to ("https://map.yahoo.co.jp/place?lat=" & strLat & "&lon=" & strLong & "&zoom=15&maptype=twoTones")
###
set strMapURL to ("https://maps.gsi.go.jp/vector/#15/" & strLat & "/" & strLong & "/&ls=vstd&disp=1&d=l")
###
set strMapURL to ("https://www.jma.go.jp/bosai/nowc/#lat:" & strLat & "/lon:" & strLong & "/zoom:15/")
*)
###GoogleURL
set strMapURL to ("https://www.google.com/maps/@" & strLat & "," & strLong & ",17z?entry=ttu") as text
##
set strDefaultAnswer to (strIP & "\n" & strMapURL & "\n")

##############################
#####ダイアログ
##############################
##前面に出す
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
###アイコンパス
set aliasIconPath to POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns" as alias
set strMes to ("戻り値です") as text
set recordResult to (display dialog strMes with title "選んでください" default answer strDefaultAnswer buttons {"IPアドレスをクリップボードにコピー", "キャンセル", "位置情報を開く"} default button "位置情報を開く" cancel button "キャンセル" giving up after 20 with icon aliasIconPath without hidden answer)
###クリップボードコピー
if button returned of recordResult is "位置情報を開く" then
  tell application "Finder"
    
    open location strMapURL
  end tell
end if

###クリップボードコピー
if button returned of recordResult is "IPアドレスをクリップボードにコピー" then
  set strText to (text returned of recordResult) as text
  try
    ####ペーストボード宣言
    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
    set ocidText to (refMe's NSString's stringWithString:(strIP))
appPasteboard's clearContents()
appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
  on error
    tell application "Finder"
      set the clipboard to strIP as text
    end tell
  end try
end if



|

[valueForKeyPath]非圧縮ZIPを解凍して内部のデータから値を取得する(curveファイルにアートボード縦横サイズを付与する)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
curveファイルは非圧縮ZIPファイルで
内部に複数のファイルを保持しています。
解凍して内部のJSONからアートボードの縦横を取得しています。
*)
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "UniformTypeIdentifiers"
use scripting additions

property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()

###デフォルトロケーション
set ocidForDirArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopPathURL to ocidForDirArray's firstObject()
set aliasDefaultLocation to (ocidDesktopPathURL's absoluteURL()) as alias

set listUTI to {"com.vladidanila.vectornator", "com.linearity.curve"}

#####ダイアログを前面に
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if

set strMes to ("curveファイルを選んでください") as text
set strPrompt to ("curveファイルを選んでください") as text


set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasDefaultLocation of type listUTI with invisibles and multiple selections allowed without showing package contents) as list

repeat with itemAliasFilePath in listAliasFilePath
  set theFilePath to POSIX path of itemAliasFilePath as text
  set ocidFilePathStr to (refMe's NSString's stringWithString:(theFilePath))
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
  ###リネームに必要な値
  set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
  set strExtensionName to (ocidFilePathURL's pathExtension()) as text
  set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
  set strBaseFileName to (ocidBaseFilePathURL's lastPathComponent()) as text
  ##コマンド用のパス
  set strFilePath to (ocidFilePathURL's |path|()) as text
  ###コマンド整形
  set strCommandText to ("/usr/bin/unzip -c \"" & strFilePath & "\" Document.json")
  ###実行
  set strCommandResponse to (do shell script strCommandText) as text
  ### コマンドの戻り値からJOSN部のみ取り出す
  set ocidCommandResponse to (refMe's NSString's stringWithString:(strCommandResponse))
  set ocidCommandResponseArray to (ocidCommandResponse's componentsSeparatedByString:("\r"))
  set ocidJsonDoc to (ocidCommandResponseArray's objectAtIndex:2)
  ###NSDATA化
  set ocidJsonData to (ocidJsonDoc's dataUsingEncoding:(refMe's NSUTF8StringEncoding))
  ###JSON初期化
  set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidJsonData) options:(refMe's NSJSONReadingAllowFragments) |error|:(reference))
  set ocidJsonData to item 1 of listJSONSerialization
  ###ディレクトリに格納して
  set ocidJsonDict to (refMe's NSDictionary's alloc()'s initWithDictionary:(ocidJsonData))
  ###値を取り出す
  set strUUIDArray to (ocidJsonDict's valueForKeyPath:("drawing.artboardPaths"))
  set strUUID to strUUIDArray's firstObject()
  log strUUID as text
  #############################################
  set strCommandText to ("/usr/bin/unzip -c \"" & strFilePath & "\" '" & strUUID & "'")
  set strCommandResponse to (do shell script strCommandText) as text
  ### コマンドの戻り値からJOSN部のみ取り出す
  set ocidCommandResponse to (refMe's NSString's stringWithString:(strCommandResponse))
  set ocidCommandResponseArray to (ocidCommandResponse's componentsSeparatedByString:("\r"))
  set ocidJsonDoc to (ocidCommandResponseArray's objectAtIndex:2)
  ###NSDATA化
  set ocidJsonData to (ocidJsonDoc's dataUsingEncoding:(refMe's NSUTF8StringEncoding))
  ###JSON初期化
  set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidJsonData) options:(refMe's NSJSONReadingAllowFragments) |error|:(reference))
  set ocidJsonData to item 1 of listJSONSerialization
  ###ディレクトリに格納して
  set ocidJsonDict to (refMe's NSDictionary's alloc()'s initWithDictionary:(ocidJsonData))
  ###修正箇所
  set strWidth to (ocidJsonDict's valueForKeyPath:("frame.width"))
  set strHeight to (ocidJsonDict's valueForKeyPath:("frame.height"))
  if strWidth is (missing value) then
    ###値を取り出す
    set strWidth to (ocidJsonDict's valueForKeyPath:("artboards.frame.width"))
    set strHeight to (ocidJsonDict's valueForKeyPath:("artboards.frame.height"))
  end if
  
  ###新しいファイル名
  ###vectornatorを廃止
  set strExtensionName to "curve" as text
  set strNewFileName to (strBaseFileName & "." & strWidth & "x" & strHeight & "." & strExtensionName) as text
  ###新しいURL
  set ocidNewFilePathURL to (ocidContainerDirPathURL's URLByAppendingPathComponent:(strNewFileName))
  ###移動(リネーム)
  set listDone to (appFileManager's moveItemAtURL:(ocidFilePathURL) toURL:(ocidNewFilePathURL) |error|:(reference))
end repeat




|

[JSON]為替計算


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.6"
use framework "Foundation"
use framework "AppKit"
use framework "UniformTypeIdentifiers"
use scripting additions
property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807

##########################################
###【1】ダイアログ
## クリップボードの中身取り出し
###初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to appPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    log "テキストなし"
    set strReadString to "入力してください" as text
  end if
end if

###ダイアログ
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set aliasIconPath to (POSIX file "/System/Library/CoreServices/Tips.app/Contents/Resources/AppIcon.icns") as alias
set strTitle to ("入力してください") as text
set strMes to ("【通貨入力】数字で入力してください\r") as text
set recordResult to (display dialog strMes with title strTitle default answer strReadString buttons {"キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 30 with icon aliasIconPath without hidden answer)
if (gave up of recordResult) is true then
return "時間切れです"
else if (button returned of recordResult) is "キャンセル" then
return "キャンセルです"
else
  set strReturnedText to (text returned of recordResult) as text
end if
###########################
###戻り値
set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
###タブと改行を除去しておく
set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextM's appendString:(ocidResponseText)
##改行除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\r") withString:("")
##タブ除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\t") withString:("")
####戻り値を半角にする
set ocidNSStringTransform to (refMe's NSStringTransformFullwidthToHalfwidth)
set ocidTextM to (ocidTextM's stringByApplyingTransform:ocidNSStringTransform |reverse|:false)
##
set numImput to (ocidTextM as text) as number



##########################################
###【JSON-1】URLをNSURL
set strURL to "http://www.gaitameonline.com/rateaj/getrate" as text
set ocidURLString to refMe's NSString's stringWithString:(strURL)
set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLString)

##########################################
###【JSON-2】URLのコンテンツ(応答)をNSDATAに
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(refMe's NSDataReadingMappedIfSafe) |error|:(reference)
set coidReadData to item 1 of listReadData

##########################################
### 【JSON-3】JSON初期化
set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(coidReadData) options:(refMe's NSJSONReadingMutableContainers) |error|:(reference))
set ocidJsonData to item 1 of listJSONSerialization
##########################################
####【JSON-4】アクセスした日時を取得しておく
set strDateNo to doGetDateNo("yyyy/MM/dd-hh:mm:ss")

##########################################
####【JSON-5】レコードに格納
set ocidJsonDict to refMe's NSDictionary's alloc()'s initWithDictionary:(ocidJsonData)
set ocidAllKeys to ocidJsonDict's allKeys()
--> quotes
##########################################
####【JSON-6】quotesのValue=ARRAYを取得
set ocidJsonArrayM to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
ocidJsonArrayM's addObjectsFromArray:(ocidJsonData's objectForKey:(ocidAllKeys's firstObject()))

##########################################
####【JSON-7】Arrayの数だけ繰り返し
###ダイアログ用のリスト
set ocidDialogueArrayM to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
###quotesの数だけ繰り返し
repeat with itemJsonArrayM in ocidJsonArrayM
  set ocidQuotesDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidQuotesDict's setDictionary:(itemJsonArrayM))
  set ocidAllKeys to ocidQuotesDict's allKeys()
  ## log ocidAllKeys as list
  --> (*low, high, currencyPairCode, open, bid, ask*)
  ###ペアコードを格納する
  set strPairCode to (ocidQuotesDict's valueForKey:("currencyPairCode")) as text
(ocidDialogueArrayM's addObject:(strPairCode))
end repeat



##########################################
####【JSON-8】ダイアログ
###ABC順に並び替える
set ocidDescriptor to (refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(true) selector:"localizedStandardCompare:")
ocidDialogueArrayM's sortUsingDescriptors:{ocidDescriptor}
set listDialogueArrayM to ocidDialogueArrayM as list

tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  ###ダイアログを前面に出す
  tell application "Finder"
    activate
  end tell
else
  tell current application
    activate
  end tell
end if
try
  set listResponse to (choose from list listDialogueArrayM with title "選んでください" with prompt "ペアコードを選んでください" default items (item 23 of listDialogueArrayM) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしました"
end if

set strResponse to (item 1 of listResponse) as text

##########################################
####【8】情報を取得整理する

###quotesの数だけ繰り返し
repeat with itemJsonArrayM in ocidJsonArrayM
  set ocidQuotesDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidQuotesDict's setDictionary:(itemJsonArrayM))
  set ocidAllKeys to ocidQuotesDict's allKeys()
  ###ダイアログで選んだペアコードから各種値を取り出す
  set strPairCode to (ocidQuotesDict's valueForKey:("currencyPairCode")) as text
  if strPairCode is strResponse then
    set strlow to (ocidQuotesDict's valueForKey:("low"))
    set strhigh to (ocidQuotesDict's valueForKey:("high"))
    set stropen to (ocidQuotesDict's valueForKey:("open"))
    set strbid to (ocidQuotesDict's valueForKey:("bid"))
    set strask to (ocidQuotesDict's valueForKey:("ask"))
  end if
end repeat
###
set numhigh to (strhigh as text) as number
set numNewYen to (numhigh * numImput) as number
set strNowYen to (numNewYen as integer) as text





set strMes to ("為替レート" & strResponse & ":" & strDateNo & "\r売値:" & strbid & "\r買値:" & strask & "") as text
set strDialogueText to ("為替レート" & strResponse & ":" & strDateNo & "\r売値:" & strbid & "\r買値:" & strask & "\r\r開始:" & stropen & "\r最高値:" & strhigh & "\r最安値:" & strlow & "\r入力額:" & strReturnedText & "\r入力金額換算:" & strNowYen & "\r\r") as text

##########################################
####【9】ダイアログに表示する
set strBundleID to ("com.apple.stocks") as text
####スクリプトメニューから実行したら
if strName is "osascript" then
  ###ダイアログを前面に出す
  tell application "Finder"
    activate
  end tell
else
  tell current application
    activate
  end tell
end if

###ICON
set aliasIconPath to POSIX file "/System/Applications/Stocks.app/Contents/Resources/AppIcon.icns"

set strTitle to ("為替レート" & strResponse) as text

set recordResult to (display dialog strMes with title strTitle default answer strDialogueText buttons {"クリップボードにコピー", "中止", "再実行"} default button "再実行" cancel button "中止" giving up after 20 with icon aliasIconPath without hidden answer)

if button returned of recordResult is "クリップボードにコピー" then
  try
    set strText to text returned of recordResult as text
    ####ペーストボード宣言
    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
    set ocidText to (refMe's NSString's stringWithString:(strText))
appPasteboard's clearContents()
appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
  on error
    tell application "Finder"
      set the clipboard to strTitle as text
    end tell
  end try
end if
###自分自身を再実行
if button returned of recordResult is "再実行" then
  tell application "Finder"
    set aliasPathToMe to (path to me) as alias
  end tell
  run script aliasPathToMe
end if


##########################################
####日付のサブ
to doGetDateNo(strDateFormat)
  ####日付情報の取得
  set ocidDate to current application's NSDate's |date|()
  ###日付のフォーマットを定義
  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
ocidNSDateFormatter's setDateFormat:strDateFormat
  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
  set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo


|

[Json]地域を選んで気象庁リンクを取得する


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application

### 【1】JSONのURL
set strBaseURL to ("https://www.jma.go.jp/bosai/common/const/area.json") as text
set ocidURL to refMe's NSURL's alloc()'s initWithString:(strBaseURL)
### 【2】URLの内容JSONをNSdataに格納
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
set ocidReadData to (item 1 of listReadData)
### 【3】NSPropertyListSerializationしてレコードに
set ocidOption to (refMe's NSJSONReadingMutableContainers)
set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadData) options:(ocidOption) |error|:(reference))
set ocidPlistDictM to item 1 of listJSONSerialization
### 【4】centersを取得
set ocidCentersDict to ocidPlistDictM's objectForKey:("centers")
set ocidCentersArray to ocidCentersDict's allKeys() as list
###【5】逆引きDictを作っておく
set ocidReverseCenterDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
repeat with itemAllKeys in ocidCentersArray
  set ocidRevValue to itemAllKeys as text
  set ocidCenter to (ocidCentersDict's valueForKey:(itemAllKeys))
  set strCenterName to (ocidCenter's valueForKey:("officeName")) as text
  set ocidItemDict to (refMe's NSDictionary's dictionaryWithObject:(ocidRevValue) forKey:(strCenterName))
(ocidReverseCenterDict's addEntriesFromDictionary:(ocidItemDict))
end repeat
### 【6】ダイアログ用にセンター名を取得してリストにする
set listCenterName to {} as list
repeat with itemCentersArray in ocidCentersArray
  set ocidCenter to (ocidCentersDict's objectForKey:(itemCentersArray))
  set strCenterName to (ocidCenter's valueForKey:("officeName")) as text
  set end of listCenterName to strCenterName
end repeat

###########################
###【7】ダイアログ センター選択
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
try
  set listResponse to (choose from list listCenterName with title "選んでください" with prompt "【地方centers】選んでください" default items (item 1 of listCenterName) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしました"
else
  set strResponse to (item 1 of listResponse) as text
end if
####逆順DICTを使ってセンター番号を取得
set strCenterNo to (ocidReverseCenterDict's valueForKey:(strResponse)) as text
###########################
###【8】ダイアログで選んだセンターの子要素(office)番号を取得
set ocidCenter to (ocidCentersDict's valueForKey:(strCenterNo))
set ocidChildrenArray to ocidCenter's objectForKey:("children")
log ocidChildrenArray as list
###########################
###【9】office番号のリストから気象台レコードを作成する
set ocidOfficesDict to ocidPlistDictM's objectForKey:("offices")
###子要素 Class取り出し用のレコード
set ocidOfficeDictS to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
set listOfficeName to {} as list
###センターの子要素 気象台の分だけ繰り返し
repeat with itemChildrenArray in ocidChildrenArray
  set ocidOfficeDict to (ocidOfficesDict's objectForKey:(itemChildrenArray as text))
  set strOfficeName to (ocidOfficeDict's valueForKey:("officeName")) as text
  set ocidClassArray to (ocidOfficeDict's objectForKey:("children"))
  set ocidItemDict to (refMe's NSDictionary's dictionaryWithObject:(ocidClassArray) forKey:(strOfficeName))
(ocidOfficeDictS's addEntriesFromDictionary:(ocidItemDict))
  set end of listOfficeName to strOfficeName
end repeat
log listOfficeName as list
###########################
###【10】ダイアログ オフィス選択
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
try
  set listResponse to (choose from list listOfficeName with title "選んでください" with prompt "【地方centers】選んでください" default items (item 1 of listOfficeName) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしました"
else
  set strResponse to (item 1 of listResponse) as text
end if
###
set ocidClassArray to ocidOfficeDictS's objectForKey:(strResponse)
log ocidClassArray as list
###########################
###【11】class10sから子要素を集める
set ocidClass10sDict to ocidPlistDictM's objectForKey:("class10s")
set ocidChildArray10sM to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
repeat with itemClassArray in ocidClassArray
  set ocidClass10sArray to (ocidClass10sDict's objectForKey:(itemClassArray as text))
  set ocidClass10sChildrenArray to (ocidClass10sArray's objectForKey:("children"))
  repeat with itemChidArray in ocidClass10sChildrenArray
(ocidChildArray10sM's addObject:(itemChidArray))
  end repeat
end repeat
log ocidChildArray10sM as list

###########################
###【12】class15sから子要素を集める
set ocidClass15sDict to ocidPlistDictM's objectForKey:("class15s")
set ocidChildArray15sM to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
repeat with itemClassArray in ocidChildArray10sM
  set ocidClass15sArray to (ocidClass15sDict's objectForKey:(itemClassArray as text))
  set ocidClass15sChildrenArray to (ocidClass15sArray's objectForKey:("children"))
  repeat with itemChidArray in ocidClass15sChildrenArray
(ocidChildArray15sM's addObject:(itemChidArray))
  end repeat
end repeat

log ocidChildArray15sM as list

###########################
###【13】class20sから子要素を集める
set ocidClass20sDict to ocidPlistDictM's objectForKey:("class20s")
###
set ocidDivDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
set ocidRevDivDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
repeat with itemClassArray in ocidChildArray15sM
  set ocidClass20sArray to (ocidClass20sDict's objectForKey:(itemClassArray as text))
  set strClass20sKey to (ocidClass20sArray's objectForKey:("name")) as text
  set strClass20sValue to (itemClassArray) as text
  set ocidItemDict to (refMe's NSDictionary's dictionaryWithObject:(strClass20sValue) forKey:(strClass20sKey))
  set ocidItemRevDict to (refMe's NSDictionary's dictionaryWithObject:(strClass20sKey) forKey:(strClass20sValue))
(ocidDivDict's addEntriesFromDictionary:(ocidItemDict))
(ocidRevDivDict's addEntriesFromDictionary:(ocidItemRevDict))
end repeat
log ocidDivDict as record
log ocidRevDivDict as record
set listAllKey to (ocidDivDict's allKeys()) as list

###########################
###【14】最終的な選択ダイアログ
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
try
  set listResponse to (choose from list listAllKey with title "選んでください" with prompt "選んでください" default items (item 1 of listAllKey) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしました"
else
  set strResponse to (item 1 of listResponse) as text
end if
set ocidValueNO to ocidDivDict's valueForKey:(strResponse)
set strValueNO to ocidValueNO as text
log strValueNO



########################################
##HTML 基本構造
###スタイル
set strStylle to "<style>#bordertable {padding: 10px;width: 100%;margin: 0;border-collapse: collapse;border-spacing: 0;word-wrap: break-word;} #bordertable table { width: 80%;margin: 0px;padding: 0px;border: 0px;border-spacing:0px;border-collapse: collapse;} #bordertable caption { font-weight: 900;} #bordertable thead { font-weight: 600;border-spacing:0px;} #bordertable td {border: solid 1px #666666;padding: 5px;margin: 0px;word-wrap: break-word;border-spacing:0px;} #bordertable tr {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;} #bordertable th {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;}</style>"
###ヘッダー部
set strHead to "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>[" & strValueNO & "]" & strResponse & "</title>" & strStylle & "</head><body>"
###最後
set strHtmlEndBody to "</body></html>"
###HTML書き出し用のテキスト初期化
set ocidHTMLString to refMe's NSMutableString's alloc()'s initWithCapacity:0
####
(ocidHTMLString's appendString:strHead)

#########
###テーブルの開始部
set strHTML to ("<div id=\"bordertable\"><table><caption title=\"タイトル\">検索語句:" & strResponse & " 検索結果:" & strValueNO & "件</caption>") as text
set strHTML to (strHTML & "<thead title=\"項目名称\"><tr><th title=\"項目1\" scope=\"row\" >連番</th><th title=\"項目2\" scope=\"col\"> リンク1 </th><th title=\"項目3\" scope=\"col\">リンク2</th><th title=\"項目4\" scope=\"col\">リンク3</th><th title=\"項目5\" scope=\"col\"> リンク4</th><th title=\"項目6\" scope=\"col\">リンク5</th><th title=\"項目7\" scope=\"col\">リンク6</th><th title=\"項目8\" scope=\"col\">リンク7</th><th title=\"項目9\" scope=\"col\">リンク8</th></tr></thead><tbody title=\"検索結果一覧\" >") as text
(ocidHTMLString's appendString:(strHTML))
##############################
###リンク防災
set strMapURL to ("https://www.jma.go.jp/bosai/#pattern=default&area_type=class20s&area_code=" & strValueNO & "")
set strLINK1 to "<a href=\"" & strMapURL & "\" target=\"_blank\">防災情報</a>"
###リンク天気予報
set strMapURL to ("https://www.jma.go.jp/bosai/forecast/#area_type=class20s&area_code=" & strValueNO & "")
set strLINK2 to "<a href=\"" & strMapURL & "\" target=\"_blank\">天気予報</a>"
### 追加 注意報
set strMapURL to ("https://www.jma.go.jp/bosai/warning/#area_type=class20s&area_code=" & strValueNO & "")
set strLINK3 to "<a href=\"" & strMapURL & "\" target=\"_blank\">警報注意報</a>"
###リンクアメダス
set strMapURL to ("https://www.jma.go.jp/bosai/map.html#contents=amedas&area_type=class20s&area_code=" & strValueNO & "")
set strLINK4 to "<a href=\"" & strMapURL & "\" target=\"_blank\">アメダス</a>"
###リンク雨雲
set strMapURL to ("https://www.jma.go.jp/bosai/nowc/#area_type:class20s/area_code:" & strValueNO & "/")
set strLINK5 to "<a href=\"" & strMapURL & "\" target=\"_blank\">雨雲の動き</a>"
###リンク早期
set strMapURL to ("https://www.jma.go.jp/bosai/probability/#area_type=class20s&lang=ja&area_code=" & strValueNO & "")
set strLINK6 to "<a href=\"" & strMapURL & "\" target=\"_blank\">早期注意情報</a>"
###リンク津波
set strMapURL to ("https://www.jma.go.jp/bosai/map.html#contents=tsunami&area_type=class20s&from=bosaitop&area_code=" & strValueNO & "")
set strLINK7 to "<a href=\"" & strMapURL & "\" target=\"_blank\">津波</a>"
###リンク噴火
set strMapURL to ("https://www.jma.go.jp/bosai/map.html#contents=volcano&area_type=class20s&from=bosaitop&area_code=" & strValueNO & "")
set strLINK8 to "<a href=\"" & strMapURL & "\" target=\"_blank\">噴火</a>"

###HTMLにして
set strHTML to ("<tr><th title=\"連番\" scope=\"row\">1</th><td title=\"リンク1\"><b>" & strLINK1 & "</b></td><td title=\"リンク2\">" & strLINK2 & "</td><td title=\"リンク3\">" & strLINK3 & "</td><td title=\"リンク4\">" & strLINK4 & "</td><td title=\"リンク5\">" & strLINK5 & "</td><td title=\"リンク6\">" & strLINK6 & "</td><td title=\"リンク7\">" & strLINK7 & "</td><td title=\"リンク8\">" & strLINK8 & "</td></tr>") as text
(ocidHTMLString's appendString:(strHTML))
set strHTML to ("</tbody><tfoot><tr><th colspan=\"8\" title=\"フッター表の終わり\" scope=\"row\"><a href=\"https://www.jma.go.jp//\" target=\"_blank\">www.jma.go.jp</a></th></tr></tfoot></table></div>") as text
####テーブルまでを追加
(ocidHTMLString's appendString:(strHTML))
####終了部を追加
(ocidHTMLString's appendString:(strHtmlEndBody))

###ディレクトリ
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTempDirURL to appFileManager's temporaryDirectory()
set ocidUUID to refMe's NSUUID's alloc()'s init()
set ocidUUIDString to ocidUUID's UUIDString
set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
###パス

set strFileName to ((strValueNO) & ".html") as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
###ファイルに書き出し
set listDone to ocidHTMLString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
####テキストエディタで開く
set aliasFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
(*
tell application "TextEdit"
activate
open file aliasFilePath
end tell
*)
tell application "Safari"
  activate
  open file aliasFilePath
end tell




|

[JSON]市区町村コード取得


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application

###########################
###都道府県番号レコード
set recordPrefCode 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 record
###Dictに格納
set recordPrefCodeDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
recordPrefCodeDict's setDictionary:(recordPrefCode)
###キーと値をそれぞれArrayにしておく
set ocidAllKeys to recordPrefCodeDict's allKeys()
### 逆順Dictを初期化
set ocidReversePrefCodeDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
repeat with itemAllKeys in ocidAllKeys
  set ocidRevValue to itemAllKeys as text
  set ocidRevKey to (recordPrefCodeDict's valueForKey:(itemAllKeys)) as text
  set ocidItemDict to (refMe's NSDictionary's dictionaryWithObject:(ocidRevValue) forKey:(ocidRevKey))
(ocidReversePrefCodeDict's addEntriesFromDictionary:(ocidItemDict))
end repeat
##AllValueを取って
set ocidAllValues to recordPrefCodeDict's allValues()
###AllValue値のArrayをソート
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(true) selector:("localizedStandardCompare:")
set ocidDescriptorArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
ocidDescriptorArray's addObject:(ocidDescriptor)
set ocidSortedValues to (ocidAllValues's sortedArrayUsingDescriptors:(ocidDescriptorArray))
###ダイアログ用のリスト
set listChooser to {} as list
###ソート済みの値Arrayを順番に
repeat with itemSortedValues in ocidSortedValues
  set strItemSortedValues to itemSortedValues as text
  set strPrefName to (ocidReversePrefCodeDict's valueForKey:(strItemSortedValues)) as text
  set end of listChooser to (strPrefName as text)
end repeat
###########################
###ダイアログを前面に出す
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
try
  set listResponse to (choose from list listChooser with title "選んでください" with prompt "選んでください" default items (item 1 of listChooser) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしました"
else
  set strResponse to (item 1 of listResponse) as text
end if
set ocidValueNO to recordPrefCodeDict's valueForKey:(strResponse)
set strValueNO to ocidValueNO as text

###########################
##
set strBaseURL to ("https://www.land.mlit.go.jp/webland_english/api/CitySearch") as text
set strBaseURL to ("https://www.land.mlit.go.jp/webland/api/CitySearch") as text
set ocidURL to refMe's NSURL's alloc()'s initWithString:(strBaseURL)
##コンポーネント初期化
set ocidComponents to refMe's NSURLComponents's componentsWithURL:(ocidURL) resolvingAgainstBaseURL:true
##クエリー格納用Array
set ocidQueryItemArray to refMe's NSMutableArray's alloc()'s initWithCapacity:0
set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("area") value:(strValueNO)
ocidQueryItemArray's addObject:(ocidQueryItem)
ocidComponents's setQueryItems:(ocidQueryItemArray)
### 【1】JSONのURL
set ocidAPIURL to ocidComponents's |URL|
log ocidAPIURL's absoluteString() as text

### 【2】URLの内容JSONをNSdataに格納
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidAPIURL) options:(ocidOption) |error|:(reference)
set ocidReadData to (item 1 of listReadData)

### 【3】NSPropertyListSerializationしてレコードに
set ocidOption to (refMe's NSJSONReadingMutableContainers)
set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadData) options:(ocidOption) |error|:(reference))
set ocidPlistDictM to item 1 of listJSONSerialization
### 【4】Data=Arrayを取り出す
set ocidDataArray to ocidPlistDictM's objectForKey:("data")
### 【5】4のArrayをDictにしていく
set ocidDataDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
repeat with itemDataArray in ocidDataArray
  set strID to (itemDataArray's valueForKey:("id")) as text
  set strValue to (itemDataArray's valueForKey:("name")) as text
  set ocidItemDict to (refMe's NSDictionary's dictionaryWithObject:(strValue) forKey:(strID))
(ocidDataDict's addEntriesFromDictionary:(ocidItemDict))
end repeat

### 【6】DictからAllKeyを取り出す
set ocidAllKeysArray to ocidDataDict's allKeys()
### 【7】逆順Dictを初期化
set ocidReverseDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
repeat with itemAllKeysArray in ocidAllKeysArray
  set ocidRevValue to itemAllKeysArray as text
  set ocidRevKey to (ocidDataDict's valueForKey:(itemAllKeysArray)) as text
  set ocidItemDict to (refMe's NSDictionary's dictionaryWithObject:(ocidRevValue) forKey:(ocidRevKey))
(ocidReverseDict's addEntriesFromDictionary:(ocidItemDict))
end repeat
### 【8】5で取り出したDictからAllValue全ての値を取り出す
set ocidAllValueArray to ocidDataDict's allValues()

###ダイアログ用のリスト
set listAllValueArray to ocidAllValueArray as list
###########################
###ダイアログを前面に出す
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
try
  set listResponse to (choose from list listAllValueArray with title "選んでください" with prompt "選んでください" default items (item 1 of listAllValueArray) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしました"
else
  set strResponse to (item 1 of listResponse) as text
end if
set strCtyNo to (ocidReverseDict's valueForKey:(strResponse)) as text

(* allValueとAllKeyが同じ順番なのを保証していないので使えないことが判明
###戻り値がArrayの何番目だったか?
set numIndex to ocidAllValueArray's indexOfObject:(strResponse)
###↑値と同じ番目にあるキーの値を市区町村コード
set strCtyNo to (ocidAllKeysArray's objectAtIndex:(numIndex)) as text
*)
###########################
###ダイアログを前面に出す
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set aliasIconPath to POSIX file "/System/Applications/Maps.app/Contents/Resources/AppIcon.icns"
set strMes to ("戻り値です\r " & strResponse & "の市区町村番号:" & strCtyNo & "") as text
set recordResult to (display dialog strMes with title "bundle identifier" default answer strCtyNo buttons {"クリップボードにコピー", "キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 20 with icon aliasIconPath without hidden answer)
if button returned of recordResult is "クリップボードにコピー" then
  try
    set strText to text returned of recordResult as text
    ####ペーストボード宣言
    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
    set ocidText to (refMe's NSString's stringWithString:(strText))
appPasteboard's clearContents()
appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
  on error
    tell application "Finder"
      set the clipboard to strTitle as text
    end tell
  end try
end if

log ocidDataDict as record

|

[JSON]JSONの取扱 その2(rootがArray形式の場合)

//JSONではキー名が同じなデータが可能
{
  "name": "John",
  "age": 30,
  "name": "Alice",
  "age": 25
}
//PLISTではキー名称を変える必要がある
{
  "name-A": "John",
  "age-A": 30,
  "name-B": "Alice",
  "age-B": 25
}


Nsjsonserialization001

ダウンロード - fontinfoexif2htmlv2.zip


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()


tell application "Finder"
  set aliasPathToMe to path to me as alias
  set aliasContainerDirPath to container of aliasPathToMe as alias
end tell
set strContainerDirPath to POSIX path of aliasContainerDirPath as text
########################################
### 設定項目
### exiftoolへのパス
########################################
set strExifPath to (strContainerDirPath & "bin/exiftool") as text

########################################
####出力先(再起動時に削除されます)
set ocidTemporaryDirPathURL to appFileManager's temporaryDirectory
set ocidVarFoldersDirURL to ocidTemporaryDirPathURL's URLByDeletingLastPathComponent()
set ocidTemporaryItemsPathURL to ocidVarFoldersDirURL's URLByAppendingPathComponent:"TemporaryItems"
##フォルダを作る
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listDone to appFileManager's createDirectoryAtURL:(ocidTemporaryItemsPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error|:(reference)
set aliasTemporaryItems to (ocidTemporaryItemsPathURL's absoluteURL()) as alias
########################################
#######ファイル選択
#####ダイアログを前面に
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set ocidUserLibraryPathURLArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidUserLibraryPathURL to ocidUserLibraryPathURLArray's firstObject()
set ocidFilePathURL to ocidUserLibraryPathURL's URLByAppendingPathComponent:("Fonts") isDirectory:true
set aliasDefaultLocation to (ocidFilePathURL's absoluteURL()) as alias
set listUTI to {"public.font"}
set strPromptText to "フォント・ファイルを選んでください" as text
set strMesText to "フォント・ファイルを選んでください" as text
set aliasFilePath to (choose file strMesText with prompt strPromptText default location (aliasDefaultLocation) of type listUTI with invisibles without multiple selections allowed and showing package contents) as alias
####入力ファイル関連
set strFilePath to POSIX path of aliasFilePath as text
###NSストリングに
set ocidFilePath to refMe's NSString's stringWithString:strFilePath
###NSURLに
set ocidFilePathURL to refMe's NSURL's fileURLWithPath:ocidFilePath
##ファイル名取得
set strFileName to (ocidFilePathURL's lastPathComponent) as text

########################################
######出力ファイル
##ファイル名
set strFileName to (strFileName & ".html") as text

set aliasSaveFilePath to (choose file name with prompt "htmlのファイル名を付けてください" default name strFileName default location aliasTemporaryItems) as «class furl»

set strSaveFilePath to (POSIX path of aliasSaveFilePath) as text
###NSストリングに
set ocidSaveFilePath to refMe's NSString's stringWithString:(strSaveFilePath)
###NSURLに
set ocidSaveFilePathURL to refMe's NSURL's fileURLWithPath:(ocidSaveFilePath)
##拡張子
set strFileExtension to (ocidSaveFilePathURL's pathExtension) as text
###拡張子つけ忘れ対策
if strFileExtension is not "html" then
  set strSaveFilePath to (POSIX path of aliasSaveFilePath & ".html") as text
end if

########################################
###【1】データ取得 JSON出力
try
  set theCommandText to ("\"" & strExifPath & "\" -json \"" & strFilePath & "\"") as text
  set strResponseJosn to (do shell script theCommandText) as text
on error
  log "たぶんexiftoolの非対応のファイルタイプです"
end try
###【2】NSStringにテキストに格納して
set ocidReadDataJson to refMe's NSString's stringWithString:strResponseJosn
###【3】NSConcreteMutableDataに変換
set ocidReadDataUTF to ocidReadDataJson's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
###【4】NSInlineDataデータ初期化
set ocidReadData to (refMe's NSData's alloc()'s initWithData:(ocidReadDataUTF))
###【5】NSJSONSerialization
set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:ocidReadData options:0 |error|:(reference))
set ocidJsonData to (item 1 of listJSONSerialization)
-->(*__NSSingleObjectArrayI*)
####解説
(*
exiftoolの書き出すJSONはrootがArray構造から始まっているので
PlistにするにはDictに変換なりする必要がある
幸い『[{}]』といったシングルArray構造なので
Arrayから最初のOBJECTを取り出せばDICTレコード構造になる
*)
set ocidJsonDict to (ocidJsonData's firstObject())
-->(*__NSDictionaryI*)
###【6】レコードをNSDictionaryとして格納
set ocidJsonDict to (refMe's NSDictionary's alloc()'s initWithDictionary:ocidJsonDict)
###【7】NSPropertyListSerialization's
set ocidFromat to (refMe's NSPropertyListXMLFormat_v1_0)
set listPlistData to refMe's NSPropertyListSerialization's dataWithPropertyList:(ocidJsonDict) format:(ocidFromat) options:0 |error|:(reference)
set ocidPlistData to item 1 of listPlistData

###保存先
set ocidSaveDirPathURL to ocidSaveFilePathURL's URLByDeletingLastPathComponent()
set aliasSaveDirPath to ocidSaveDirPathURL's absoluteURL() as alias

set strPlistFileName to (strFileName & ".plist") as text
set ocidPlistFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strPlistFileName)
###【8】保存
set ocidOption to (refMe's NSDataWritingAtomic)
set boolWritetoUrlArray to ocidPlistData's writeToURL:(ocidPlistFilePathURL) options:(ocidOption) |error|:(reference)

tell application "Finder"
  open folder aliasSaveDirPath
end tell
########################################
#######HTML 基本構造
###スタイル
set strStylle to "<style>#bordertable {padding: 10px;width: 100%;margin: 0;border-collapse: collapse;border-spacing: 0;word-wrap: break-word;} #bordertable table { width: 580px;margin: 0px;padding: 0px;border: 0px;border-spacing:0px;border-collapse: collapse;} #bordertable caption { font-weight: 900;} #bordertable thead { font-weight: 600;border-spacing:0px;} #bordertable td {border: solid 1px #666666;padding: 3px;margin: 0px;word-wrap: break-word;border-spacing:0px;} #bordertable tr {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;} #bordertable th {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;}</style>"
###ヘッダー部
set strHead to "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>[Exif]" & strFileName & "</title>" & strStylle & "</head><body>"
###ボディ
set strBody to ""
###最後
set strHtmlEndBody to "</body></html>"
###HTML書き出し用のテキスト初期化
set ocidHTMLString to refMe's NSMutableString's alloc()'s initWithCapacity:0
####
(ocidHTMLString's appendString:strHead)
###テーブル構造
set strTableHeader to "<div id=\"bordertable\"><table><caption>Exif情報:" & strFileName & "</caption><thead title=\"表の項目について\"><tr><th title=\"項目の番号が最初\" style=\"width: 36px;\" scope=\"row\" >項番</th><th title=\"キーの名前が2番目\" scope=\"col\">キーの名前</th><th title=\"キーの値は3番目になっています\" scope=\"col\">キーの値</th></thead><tbody title=\"表の始まりです\">" as text
(ocidHTMLString's appendString:strTableHeader)

####JSONの全てのキーを取得して
set ocidAllKeys to ocidJsonDict's allKeys()
set numLineNO to 0
####キーの種類だけ繰り返し
repeat with objKey in ocidAllKeys
  set strKey to objKey as text
  ####キーの値を取り出し
  set strValue to (ocidJsonDict's valueForKey:(strKey)) as text
  
  set strKey to doHtmlEntitiesEnc(strKey)
  set strValue to doHtmlEntitiesEnc(strValue)
  
  ####内容によって表示させるための分岐
  if strKey is "ExifToolVersion" then
    ###キーと値を保存
    set strHTMLTagFooterKey to strKey as text
    set strHTMLTagFooterValue to strValue as text
    ####例外処理
  else if strKey is "Directory" then
    set numLineNO to numLineNO + 1 as number
    set strHTMLTag to "<tr><th title=\"項番:" & strKey & "\" scope=\"row\">" & numLineNO & "</th><td title=\"キー:" & strKey & "について\">" & strKey & "</td><td title=\"キー:" & strKey & "の値\">非表示にしています</td></tr>" as text
  else if strKey is "SourceFile" then
    set numLineNO to numLineNO + 1 as number
    set strHTMLTag to "<tr><th title=\"項番:" & strKey & "\" scope=\"row\">" & numLineNO & "</th><td title=\"キー:" & strKey & "について\">" & strKey & "</td><td title=\"キー:" & strKey & "の値\">非表示にしています</td></tr>" as text
  else
    ###普通はこの処理
    set numLineNO to numLineNO + 1 as number
    set strHTMLTag to "<tr><th title=\"項番:" & strKey & "\" scope=\"row\">" & numLineNO & "</th><td title=\"キー:" & strKey & "について\">" & strKey & "</td><td title=\"キー:" & strKey & "の値\">" & strValue & "</td></tr>" as text
  end if
  ####できたタグを追加
(ocidHTMLString's appendString:strHTMLTag)
  
end repeat
###最後にバージョンを入れる
set numLineNO to numLineNO + 1 as number
###最後のtfoot項目
set strHTMLTagFooter to "</tbody><tfoot title=\"表の終わりです\"><tr><th title=\"項番:" & numLineNO & "\" scope=\"row\">" & numLineNO & "</th><td title=\"キーの名前\">ExifToolVersion</td><td title=\"キー:" & strHTMLTagFooterKey & "の値\">ExifTool:" & strHTMLTagFooterValue & "で作成しました</td></tr></tfoot></table></div>" as text
###タグを全部追加して
(ocidHTMLString's appendString:strHTMLTagFooter)
ocidHTMLString's appendString:strHtmlEndBody
###ファイルに書き出し
set boolWritetoUrlArray to ocidHTMLString's writeToFile:strSaveFilePath atomically:true encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
(*
####テキストエディタで開く
log strSaveFilePath
tell application "TextEdit"
activate
open (POSIX file strSaveFilePath as alias)
end tell
*)
####サファリで開く
set strOpenURL to ocidSaveFilePathURL's absoluteString() as text
tell application "Safari"
  activate
  make new document with properties {name:"MDLS2HTMLv2"}
  tell window 1
    open location strOpenURL
  end tell
end tell
########################################
### キー名と値にHTMLの要素があるケースがあるので
### HtmlEntities変換
########################################

to doHtmlEntitiesEnc(argTEXT)
  
  ###置換レコード
  ## set recordEntityMap to {|&|:"&amp;", |<|:"&lt;", |>|:"&gt;", |"|:"&quot;", |'|:"&apos;", |=|:"&#x3D;", |+|:"&#x2B;"} as record
  set recordEntityMap to {|<|:"&lt;", |>|:"&gt;", |"|:"&quot;", |'|:"&apos;", |=|:"&#x3D;", |+|:"&#x2B;", |©|:"&copy;", |®|:"&reg;", |™|:"&trade;", |€|:"&euro;", |£|:"&pound;", |¥|:"&yen;", |...|:"&hellip;"} as record
  ###ディクショナリにして
  set ocidEntityMap to refMe's NSDictionary's alloc()'s initWithDictionary:(recordEntityMap)
  ###キーの一覧を取り出します
  set ocidAllKeys to ocidEntityMap's allKeys()
  
  ##通常テキストの場合
  set strText to argTEXT as text
  ###選択中テキスト
  set ocidText to refMe's NSString's stringWithString:(strText)
  ###可変テキストにして
  set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:0
ocidTextM's setString:(ocidText)
  ###&だけ先に処理しておく
  set ocidTextM to (ocidTextM's stringByReplacingOccurrencesOfString:("&") withString:("&amp;"))
  ###取り出したキー一覧を順番に処理
  repeat with itemAllKey in ocidAllKeys
    set strItemKey to itemAllKey as text
    ##キーの値を取り出して
    set strValue to (ocidEntityMap's valueForKey:(itemAllKey)) as text
    ##置換
    set ocidTextM to (ocidTextM's stringByReplacingOccurrencesOfString:(strItemKey) withString:(strValue))
    ##次の変換に備える
    set ocidTextM to ocidTextM
  end repeat
  
return (ocidTextM as text)
end doHtmlEntitiesEnc

|

[JSON]JSONの取扱 その1(rootがDict形式の場合)

Plistフォーマットは基本 キー名称とバリュー値の対になっている
JSONとの違い(JSONデータをPLISTに変換する時に配慮が必要な事項)
【1】ROOT構造
JsonとPlistは『ほぼ』同じだが、JSONはrootをArray構造にする事が可能だが
PlistフォーマットはrootはDict 辞書レコード形式になる
【2】辞書における同名のキー名称
JSONは辞書形式の中で同じキー名を使う事ができる
DictにしてPlistへ
Serialization001

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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application


###都道府県番号レコード
set recordPrefCode to {|北海道|:"1", |青森県|:"2", |岩手県|:"3", |宮城県|:"4", |秋田県|:"5", |山形県|:"6", |福島県|:"7", |茨城県|:"8", |栃木県|:"9", |群馬県|:"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 record
###Dictに格納
set recordPrefCodeDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
recordPrefCodeDict's setDictionary:(recordPrefCode)
###キーと値をそれぞれArrayにしておく
set ocidAllKeys to recordPrefCodeDict's allKeys()
set ocidAllValues to recordPrefCodeDict's allValues()
###値のArrayをソート
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(true) selector:("localizedStandardCompare:")
set ocidDescriptorArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
ocidDescriptorArray's addObject:(ocidDescriptor)
set ocidSortedValues to (ocidAllValues's sortedArrayUsingDescriptors:(ocidDescriptorArray))
###ダイアログ用のリスト
set listChooser to {} as list
###ソート済みの値Arrayを順番に
repeat with itemSortedValues in ocidSortedValues
  ###ソート済みの値が何番目だったか?
  set numIndexNo to (ocidAllValues's indexOfObject:(itemSortedValues))
  ###ソート済みの値と同じ位置にあるキーのArrayからキー名を取得
  set ocidKeyName to (ocidAllKeys's objectAtIndex:(numIndexNo))
  ###取り出したキーの値をダイアログ用のリストに格納
  set end of listChooser to (ocidKeyName as text)
end repeat
###########################
###ダイアログを前面に出す
tell current application
  set strName to name as text
end tell
if strName is "osascript" then
  tell application "Finder"
    activate
  end tell
else
  tell current application
    activate
  end tell
end if
try
  set listResponse to (choose from list listChooser with title "選んでください" with prompt "選んでください" default items (item 1 of listChooser) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしました"
end if
###戻り値で値を取り出す
set strResponse to (item 1 of listResponse) as text
set ocidValueNO to recordPrefCodeDict's valueForKey:(strResponse)
set numValueNO to ocidValueNO as integer
###
if numValueNO < 10 then
  set strZeroSup to "00" as text
  set strSeroSup to (strZeroSup & (numValueNO as text)) as text
  set strSeroSup to (text -2 through -1 of strSeroSup) as text
  set numValueNO to strSeroSup as text
end if
### 【1】JSONのURL
set strURL to "https://apis.postcode-jp.com/api/v5/prefectures/" & numValueNO & "/cities" as text
log strURL
set ocidURLstr to refMe's NSString's stringWithString:(strURL)
set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLstr)

### 【2】URLの内容JSONをNSdataに格納
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
set ocidReadData to (item 1 of listReadData)


### 【3】NSPropertyListSerializationしてレコードに
set ocidOption to (refMe's NSJSONReadingMutableContainers)
set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadData) options:(ocidOption) |error|:(reference))
set ocidPlistDictM to item 1 of listJSONSerialization

log ocidPlistDictM as record

###【4】 NSPropertyListSerializationでPlistに XMLフォーマット
set ocidFromat to (refMe's NSPropertyListXMLFormat_v1_0)
set listPlistData to refMe's NSPropertyListSerialization's dataWithPropertyList:(ocidPlistDictM) format:(ocidFromat) options:0 |error|:(reference)
set ocidPlistData to item 1 of listPlistData

###【5】デスクトップにPlistのURL
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidDesktopDirPathURL's URLByAppendingPathComponent:("市区町村PLIST")
###保存先ディレクトリ作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
set strFileName to (strResponse & ".plist") as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName)

###【6】保存
set ocidOption to (refMe's NSDataWritingAtomic)
set boolWritetoUrlArray to ocidPlistData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference)

########################################
### 【おまけ】HTML化
set ocidDataArray to ocidPlistDictM's objectForKey:("data")

###HTML保存先ディレクトリ
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTempDirURL to appFileManager's temporaryDirectory()
set ocidUUID to refMe's NSUUID's alloc()'s init()
set ocidUUIDString to ocidUUID's UUIDString
set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
###保存先ディレクトリ作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
###パス
set strFileName to (strResponse & ".html") as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false

##HTML 基本構造
###スタイル
set strStylle to "<style>#bordertable {padding: 10px;width: 100%;margin: 0;border-collapse: collapse;border-spacing: 0;word-wrap: break-word;} #bordertable table { width: 580px;margin: 0px;padding: 0px;border: 0px;border-spacing:0px;border-collapse: collapse;} #bordertable caption { font-weight: 900;} #bordertable thead { font-weight: 600;border-spacing:0px;} #bordertable td {border: solid 1px #666666;padding: 5px;margin: 0px;word-wrap: break-word;border-spacing:0px;} #bordertable tr {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;} #bordertable th {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;}</style>"
###ヘッダー部
set strHead to "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>[Plist2HTML]" & strResponse & "</title>" & strStylle & "</head><body>"
###ボディ
set strBody to ""
###最後
set strHtmlEndBody to "</body></html>"
###HTML書き出し用のテキスト初期化
set ocidHTMLString to refMe's NSMutableString's alloc()'s initWithCapacity:0
###bodyまでを追加
(ocidHTMLString's appendString:(strHead))
#########
###テーブルの開始部
set strHTML to ("<div id=\"bordertable\"><table><caption title=\"タイトル\">市区町村</caption>") as text
set strHTML to (strHTML & "<thead title=\"項目名称\"><tr><th title=\"項目1\" scope=\"row\" > 連番 </th><th title=\"項目2\" scope=\"col\"> 名称 </th><th title=\"項目3\" scope=\"col\">市番号</th><th title=\"項目4\" scope=\"col\">かな</th><th title=\"項目5\" scope=\"col\">場所</th></tr></thead><tbody title=\"市区町村一覧\" >") as text
set numLineNo to 1 as integer
repeat with itemData in ocidDataArray
  set strCity to (itemData's valueForKey:("city")) as text
  set strCityCode to (itemData's valueForKey:("cityCode")) as text
  set strHiragana to (itemData's valueForKey:("hiragana")) as text
  set ocidLocDic to (itemData's objectForKey:("location"))
  set strLat to (ocidLocDic's valueForKey:("latitude")) as text
  set strLon to (ocidLocDic's valueForKey:("longitude")) as text
  set strMapURL to ("https://www.google.com/maps/@" & strLat & "," & strLon & ",13z")
  set strLINK to "<a href=\"" & strMapURL & "\" target=\"_blank\">LINK</a>"
  set strHTML to (strHTML & "<tr><th title=\"項番1\" scope=\"row\">" & numLineNo & "</th><td title=\"項目2\">" & strCity & "</td><td title=\"項目3\">" & strCityCode & "</td><td title=\"項目4\">" & strHiragana & "</td><td title=\"項目5\">" & strLINK & "</td></tr>") as text
  
  set numLineNo to numLineNo + 1 as integer
end repeat

set strHTML to (strHTML & "</tbody><tfoot><tr><th colspan=\"5\" title=\"フッター表の終わり\" scope=\"row\">JAPAN POSTAL CODE WEB API</th></tr></tfoot></table></div>") as text
####テーブルまでを追加
(ocidHTMLString's appendString:(strHTML))
####終了部を追加
(ocidHTMLString's appendString:(strHtmlEndBody))

###ファイルに書き出し
set listDone to ocidHTMLString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
####テキストエディタで開く
set aliasFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias

tell application "TextEdit"
  activate
  open file aliasFilePath
end tell




|

[Bash]JSONから値を取得する(plist変換)


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

#!/bin/bash
#com.cocolog-nifty.quicktimer.icefloe
#################################################
###【1】ダウンロード起動時に削除する項目
USER_TEMP_DIR=$(/usr/bin/mktemp -d)
/bin/echo "起動時に削除されるディレクトリ:" "$USER_TEMP_DIR"

########################################
###【2】JSON ダウンロード
STR_JSON_URL="https://www.jma.go.jp/bosai/forecast/data/forecast/130000.json"
STR_JSON_FILE_NAME=$(/usr/bin/basename "$STR_JSON_URL")
/bin/echo "ファイル名: $STR_JSON_FILE_NAME"
  if ! /usr/bin/curl -L -o "$USER_TEMP_DIR/$STR_JSON_FILE_NAME" "$STR_JSON_URL" --connect-timeout 20; then
    /bin/echo "ファイルのダウンロードに失敗しました HTTP1.1で再トライします"
    if ! /usr/bin/curl -L -o "$USER_TEMP_DIR/$STR_JSON_FILE_NAME" "$STR_JSON_URL" --http1.1 --connect-timeout 20; then
      /bin/echo "ファイルのダウンロードに失敗しました"
      exit 1
    fi
  fi
########################################
##【3】PLISTに変換
STR_PLIST_FILE_NAME="$STR_JSON_FILE_NAME"".plist"
/usr/bin/plutil -convert xml1 "$USER_TEMP_DIR/$STR_JSON_FILE_NAME" -o "$USER_TEMP_DIR/$STR_PLIST_FILE_NAME"
/bin/echo "PLIST変換OK"
/bin/sleep 1

########################################
##【4】値の取得はdefaultsかPlistBuddyで
STR_AREANAME=$(/usr/libexec/PlistBuddy -c "Print:0:timeSeries:0:areas:0:area:name" "$USER_TEMP_DIR/$STR_PLIST_FILE_NAME")
/bin/echo "$STR_AREANAME 地方の"
STR_WEATHERS=$(/usr/libexec/PlistBuddy -c "Print:0:timeSeries:0:areas:0:weathers:0" "$USER_TEMP_DIR/$STR_PLIST_FILE_NAME")
/bin/echo "天気予報: $STR_WEATHERS"

exit 0


|

より以前の記事一覧

その他のカテゴリー

Acrobat Acrobat Annotation Acrobat Dialog Acrobat Form Acrobat JS Acrobat Open Acrobat Plugin Acrobat python Acrobat Reader Acrobat Sequ Acrobat Stamps Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin System Information Admin Tools Admin Users Admin Volumes Adobe Apple AppleScript AppleScript Guide AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes AppleScript Automator AppleScript AVAsset AppleScript AVconvert AppleScript AVFoundation AppleScript AVURLAsset AppleScript BackUp AppleScript Barcode AppleScript Bash AppleScript Basic AppleScript Basic Path AppleScript Bluetooth AppleScript BOX AppleScript Browser AppleScript Calendar AppleScript CD/DVD AppleScript Choose AppleScript Chrome AppleScript CIImage AppleScript CloudStorage AppleScript Color AppleScript com.apple.LaunchServices.OpenWith AppleScript Console AppleScript Contacts AppleScript CotEditor AppleScript CURL AppleScript current application AppleScript Date&Time AppleScript delimiters AppleScript Desktop AppleScript Device AppleScript Disk AppleScript do shell script AppleScript Dock AppleScript DropBox AppleScript eMail AppleScript Encode Decode AppleScript Error AppleScript EXIFData AppleScript ffmpeg AppleScript File AppleScript Finder AppleScript Firefox AppleScript Folder AppleScript Fonts AppleScript GIF AppleScript HTML AppleScript Icon AppleScript Illustrator AppleScript Image Events AppleScript Image2PDF AppleScript ImageOptim Applescript iWork AppleScript Javascript AppleScript Jedit AppleScript Json AppleScript Label AppleScript List AppleScript locationd AppleScript LRC AppleScript LSSharedFileList AppleScript m3u8 AppleScript MakePDF AppleScript Map AppleScript Math AppleScript Microsoft AppleScript Microsoft Edge AppleScript Microsoft Excel AppleScript Mobileconfig AppleScript Mouse AppleScript Movie AppleScript Music AppleScript NetWork AppleScript Notes AppleScript NSArray AppleScript NSBitmapImageRep AppleScript NSBundle AppleScript NSCFBoolean AppleScript NSCharacterSet AppleScript NSColor AppleScript NSColorList AppleScript NSData AppleScript NSDictionary AppleScript NSError AppleScript NSEvent AppleScript NSFileAttributes AppleScript NSFileManager AppleScript NSFont AppleScript NSFontManager AppleScript NSImage AppleScript NSIndex AppleScript NSKeyedArchiver AppleScript NSKeyedUnarchiver AppleScript NSLocale AppleScript NSMutableArray AppleScript NSMutableDictionary AppleScript NSMutableString AppleScript NSNotFound AppleScript NSNumber AppleScript NSOpenPanel AppleScript NSPasteboard AppleScript NSPDFImageRep AppleScript NSpoint AppleScript NSPredicate AppleScript NSRange AppleScript NSRegularExpression AppleScript NSRunningApplication AppleScript NSScreen AppleScript NSSize AppleScript NSString AppleScript NSStringCompareOptions AppleScript NSTask AppleScript NSTimeZone AppleScript NSURL AppleScript NSURL File AppleScript NSURLBookmark AppleScript NSURLComponents AppleScript NSURLResourceKey AppleScript NSUserDefaults AppleScript NSUUID AppleScript NSView AppleScript NSWorkspace AppleScript Numbers AppleScript OAuth AppleScript ObjC AppleScript OneDrive AppleScript Osax AppleScript PDF AppleScript PDFAnnotationWidget AppleScript PDFContext AppleScript PDFDisplayBox AppleScript PDFDocumentPermissions AppleScript PDFKit AppleScript PDFnUP AppleScript PDFOutline AppleScript Photos AppleScript Photoshop AppleScript Plist System Events AppleScript PostScript AppleScript prefPane AppleScript Preview AppleScript Python AppleScript QR AppleScript QR Decode AppleScript QuickLook AppleScript QuickTime AppleScript record AppleScript Regular Expression AppleScript Reminders AppleScript ReName AppleScript Repeat AppleScript RTF AppleScript Safari AppleScript SaveFile AppleScript ScreenCapture AppleScript ScreenSaver AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript Sort AppleScript Sound AppleScript Spotlight AppleScript SRT AppleScript StandardAdditions AppleScript stringByApplyingTransform AppleScript System Events AppleScript System Settings AppleScript TemporaryItems AppleScript Terminal AppleScript Text AppleScript Text CSV AppleScript Text TSV AppleScript TextEdit AppleScript Translate AppleScript Trash AppleScript Twitter AppleScript UI AppleScript Unit Conversion AppleScript UTType AppleScript valueForKeyPath AppleScript Video AppleScript VisionKit AppleScript Visual Studio Code AppleScript webarchive AppleScript webp AppleScript Wifi AppleScript XML AppleScript XML EPUB AppleScript XML OPML AppleScript XML Plist AppleScript XML RSS AppleScript XML SVG AppleScript XML TTML AppleScript XML webloc AppleScript YouTube AppleScript Zero Suppress Applications Barcode OnLine Tools CityCode Design iPhone List Logs lsappinfo Memo Music perl PlistBuddy pluginkit postalcode ReadMe SF Symbols character id SF Symbols Entity sips Skype Slack sqlite TCC Tools Typography Video Wacom zoom