如何使用 AppleScript 从 JSON 文件中获取值? [英] How to get values from JSON file using AppleScript?

查看:55
本文介绍了如何使用 AppleScript 从 JSON 文件中获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于这个问题,

如何使用 VBScript 或批处理文件从 JSON 文件下载和获取值?

如何从类似这样的 JSON 文件中获取值,

["AA-BB-CC-MAKE-SAME.json","SS-ED-SIXSIX-TENSE.json","FF-EE-EE-EE-WW.json","ZS-WE-AS-FOUR-MINE.json","DD-RF-LATERS-LATER.json","FG-ER-DC-ED-FG.json"]

在 MAC 操作系统中使用 AppleScript?

这是 Hackoo 提供的 Windows 中 VBScript 代码的一部分,

strJson = http.responseText结果 = Extract(strJson,"(\x22(.*)\x22)")Arr = 拆分(结果,,")对于 Arr 中的每个项目wscript.echo 项目下一个'************************************************函数提取(数据,模式)Dim ore,oMatches,Match,Line设置 oRE = 新正则表达式oRE.IgnoreCase = 真oRE.Global = 真oRE.Pattern = 模式设置 oMatches = oRE.Execute(Data)如果不是 isEmpty(oMatches) 那么对于 oMatches 中的每个匹配项线 = 线 &Trim(Match.Value) &vbcrlf下一个提取 = 线万一结束函数'************************************************

在 MAC OS AppleScript 中,我只需要将 JSON 文件的值转换为单个字符串值数组的代码.上面显示的 VBScript 示例是 JSON 文件内容的样子.

解决方案

如何从类似这样的 JSON 文件中获取值,

[AA-BB-CC-MAKE-SAME.json"、SS-ED-SIXSIX-TENSE.json"、FF-EE-EE-EE-WW.json"、ZS-WE-AS-FOUR-MINE.json"、DD-RF-LATERS-LATER.json"、FG-ER-DC-ED-FG.json"]

如果你的意思是你写的,并且 JSON 文件的内容是单个数组中的六个字符串的列表,在一行中格式化,最简单的方法是将其视为文本,修剪开头和结束方括号,然后在每次出现 , 时分隔其字段.最后,每个单独的文本项也可以修剪周围的引号.

检查 VBScript,看起来它使用了一个非常相似的过程,尽管使用了正则表达式,AppleScript 没有,但在这种简单的情况下并不是特别必要.

假设上面的 JSON 数组存储在桌面上名为myfile.json"的文件中.然后:

 将 home 设置为 home 文件夹的路径将 f 设置为 home & 的 POSIX 路径桌面/myfile.json"设置 JSONstr 以读取 POSIX 文件 f# 修剪方括号将 JSONstr 设置为 JSONstr 的文本 2 到 -2# 使用逗号分隔文本字段将文本项分隔符设置为,"将 Arr 设置为 JSONstr 的文本项# 修剪 Arr 中每个项目的引号用 in Arr 重复将 a 的内容设置为文本 2 到 a 的 -2结束重复# 最后的数组到达

<块引用>

我只需要将 JSON 文件的值获取到单个字符串值数组的代码.上面显示的 VBScript 示例是 JSON 文件内容的样子.

变量 Arr 现在包含字符串值的数组(在 AppleScript 中称为 lists).您可以像这样访问其中的特定项目:

 Arr 的第 2 项 -->SS-ED-SIXSIX-TENSE.json"

<小时>

更通用的解决方案

我决定在 AppleScript 中加入一种更高级的方法来处理 JSON,部分原因是我最近一直在做很多 JSON 处理,这在我的事件范围内都是新鲜的;还要证明,使用 AppleScriptObjC,解析非常复杂的 JSON 数据不仅是可能的,而且非常简单.

我认为在这种特定情况下您不需要它,但它可能在未来的某些情况下有用.

该脚本分为三个部分:首先导入相关的 Objective-C 框架,赋予 AppleScript 额外的功能;然后,我定义了实际的处理程序本身,称为 JSONtoRecord,我将在下面描述.最后,是脚本的底部,您可以在其中输入代码并使用它做任何您喜欢的事情:

 使用框架Foundation";使用脚本添加--------------------------------------------------------------------------------属性 ca : 对当前应用程序的引用属性 NSData : 对 ca 的 NSData 的引用属性 NSDictionary : 对 ca 的 NSDictionary 的引用属性 NSJSONSerialization :对 ca 的 NSJSONSerialization 的引用属性 NSString : 对 ca 的 NSString 的引用属性 NSUTF8StringEncoding : 对 4 的引用--------------------------------------------------------------------------------来自 fp 的 JSONtoRecord本地 fp将 JSONdata 设置为 NSData 的 dataWithContentsOfFile:fp将 [x, E] 设置为 (NSJSONSerialization's ¬JSONObjectWithData:JSONdata ¬选项:0 ¬|错误|:(参考))如果 E ≠ 缺失值,则错误 E告诉 x 如果它的 isKindOfClass:NSDictionary 然后 ¬将其作为记录返回x 作为列表结束 JSONtoRecord--------------------------------------------------------------------------------###您的代码在此处##将 home 设置为 home 文件夹的路径将 f 设置为 home & 的 POSIX 路径桌面/myfile.json"来自 f 的 JSONtoRecord-->{AA-BB-CC-MAKE-SAME.json",SS-ED-SIXSIX-TENSE.json",¬-->FF-EE-EE-EE-WW.json"、ZS-WE-AS-FOUR-MINE.json"、¬-->DD-RF-LATERS-LATER.json"、FG-ER-DC-ED-FG.json"}

在脚本的底部,我调用了 JSONtoRecord 处理程序,将 myfile.json 的位置传递给它.这个处理程序的好处之一是文件是在一行上格式化还是在多行上格式化都没有关系.它还可以处理复杂的嵌套 JSON 数组.

在这些情况下,它返回的是原生 AppleScript record 对象,所有 JSON 变量都作为属性值存储在记录中.访问变量就变得非常简单了.

这实际上正是一些人已经提到的 JSON Helper 应用程序在幕后所做的事情.

一个标准(包含有效 JSON 数据的 JSON 文件除外)是文件的路径是完整写入的 posix 路径,例如/Users/CK/Desktop/myfile.json不是 ~/Desktop/myfile.json 或者更糟的是 MacintoshHD:Users:CK:Desktop:myfile.json.

In reference to this question,

How to download and get values from JSON file using VBScript or batch file?

how to get the values from JSON file that looks like this,

["AA-BB-CC-MAKE-SAME.json","SS-ED-SIXSIX-TENSE.json","FF-EE-EE-EE-WW.json","ZS-WE-AS-FOUR-MINE.json","DD-RF-LATERS-LATER.json","FG-ER-DC-ED-FG.json"]

using AppleScript in MAC OS?

Here is part of VBScript code in Windows provided by Hackoo,

strJson = http.responseText
Result = Extract(strJson,"(\x22(.*)\x22)")
Arr = Split(Result,",")
For each Item in Arr
    wscript.echo Item
Next
'******************************************
Function Extract(Data,Pattern)
   Dim oRE,oMatches,Match,Line
   set oRE = New RegExp
   oRE.IgnoreCase = True
   oRE.Global = True
   oRE.Pattern = Pattern
   set oMatches = oRE.Execute(Data)
   If not isEmpty(oMatches) then
       For Each Match in oMatches  
           Line = Line & Trim(Match.Value) & vbCrlf
       Next
       Extract = Line
   End if
End Function
'******************************************

In MAC OS AppleScript I only need the code to get the values of the JSON file to a single array of string values. The above shown example above the VBScript is the how JSON file contents looks like.

解决方案

How to get the values from JSON file that looks like this,

["AA-BB-CC-MAKE-SAME.json","SS-ED-SIXSIX-TENSE.json","FF-EE-EE-EE-WW.json","ZS-WE-AS-FOUR-MINE.json","DD-RF-LATERS-LATER.json","FG-ER-DC-ED-FG.json"]

If you actually mean what you wrote, and that the contents of the JSON file is that list of six strings in a single array, formatted on a single line, the simplest way is to treat it as text, trim the opening and closing square brackets, then delimit its fields at every occurrence of a ,. Finally, each individual text item can have the surrounding quotes trimmed as well.

Examining the VBScript, it looks like it uses a very similar process, albeit with regular expressions, which AppleScript doesn't feature but which aren't especially necessary in this simple situation.

Let's assume that the JSON array above is stored in a file on your desktop called "myfile.json". Then:

    set home to the path to home folder
    set f to the POSIX path of home & "Desktop/myfile.json"
    
    set JSONstr to read POSIX file f
    
    # Trim square brackets
    set JSONstr to text 2 thru -2 of JSONstr
    
    # Delimit text fields using comma
    set the text item delimiters to ","
    set Arr to the text items of JSONstr
    
    # Trim quotes of each item in Arr
    repeat with a in Arr
        set contents of a to text 2 thru -2 of a
    end repeat
    
    # The final array
    Arr

I only need the code to get the values of the JSON file to a single array of string values. The above shown example above the VBScript is the how JSON file contents looks like.

The variable Arr now contains the array (referred to as lists in AppleScript) of string values. You can access a particular item in it like this:

    item 2 of Arr --> "SS-ED-SIXSIX-TENSE.json"


A More General Solution

I've decided to include a more advanced way to handle JSON in an AppleScript, partly because I've been doing a lot of JSON processing quite recently and this is all fresh on my event horizon; but also to demonstrate that, using AppleScriptObjC, parsing even very complex JSON data is not only possible, but quite simple.

I don't think you'll need it in this specific case, but it could come in useful for some future situation.

The script has three sections: it starts off importing the relevant Objective-C framework that gives AppleScript additional powers; then, I define the actual handler itself, called JSONtoRecord, which I describe below. Lastly, comes the bottom of the script where you can enter your code and do whatever you like with it:

    use framework "Foundation"
    use scripting additions
    --------------------------------------------------------------------------------
    property ca : a reference to current application
    property NSData : a reference to ca's NSData
    property NSDictionary : a reference to ca's NSDictionary
    property NSJSONSerialization : a reference to ca's NSJSONSerialization
    property NSString : a reference to ca's NSString
    property NSUTF8StringEncoding : a reference to 4
    --------------------------------------------------------------------------------
    on JSONtoRecord from fp
        local fp
        
        set JSONdata to NSData's dataWithContentsOfFile:fp
        
        set [x, E] to (NSJSONSerialization's ¬
            JSONObjectWithData:JSONdata ¬
                options:0 ¬
                |error|:(reference))
        
        if E ≠ missing value then error E
        
        tell x to if its isKindOfClass:NSDictionary then ¬
            return it as record
        
        x as list
    end JSONtoRecord
    --------------------------------------------------------------------------------
    ###YOUR CODE BELOW HERE
    #
    #
    set home to the path to home folder
    set f to the POSIX path of home & "Desktop/myfile.json"
    
    JSONtoRecord from f
    
    --> {"AA-BB-CC-MAKE-SAME.json", "SS-ED-SIXSIX-TENSE.json", ¬
    --> "FF-EE-EE-EE-WW.json", "ZS-WE-AS-FOUR-MINE.json", ¬
    --> "DD-RF-LATERS-LATER.json", "FG-ER-DC-ED-FG.json"}

At the bottom of the script, I've called the JSONtoRecord handler, passing it the location of myfile.json. One of the benefits of this handler is that it doesn't matter whether the file is formatted all on one line, or over many lines. It can also handle complex, nested JSON arrays.

In those instances, what it returns is a native AppleScript record object, with all the JSON variables stored as property values in the record. Accessing the variables then becomes very simple.

This is actually exactly what the JSON Helper application that a couple of people have already mentioned does under the hood.

The one criterion (other than the JSON file containing valid JSON data) is that the path to the file is a posix path written in full, e.g. /Users/CK/Desktop/myfile.json, and not ~/Desktop/myfile.json or, even worse, Macintosh HD:Users:CK:Desktop:myfile.json.

这篇关于如何使用 AppleScript 从 JSON 文件中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆