首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用AppleScript从JSON文件中获取值?

如何使用AppleScript从JSON文件中获取值?
EN

Stack Overflow用户
提问于 2018-07-31 23:16:25
回答 2查看 4.8K关注 0票数 1

关于这个问题,

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

如何从如下所示的JSON文件中获取值,

代码语言:javascript
复制
["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代码,

代码语言:javascript
复制
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
'******************************************

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-01 09:04:18

如何从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“的文件中。然后:

代码语言:javascript
复制
    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

JSON我只需要将

文件的值转换为字符串值的单个数组的代码。上面显示的示例是VBScript文件内容的外观。

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

代码语言:javascript
复制
    item 2 of Arr --> "SS-ED-SIXSIX-TENSE.json"

更通用的解决方案

我决定在AppleScript中包含一种更高级的方法来处理JSON,部分原因是我最近一直在做大量的JSON处理,这在我的事件范围内都是新鲜的;但也是为了证明,使用AppleScriptObjC,解析甚至非常复杂的JSON数据不仅是可能的,而且非常简单。

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

该脚本有三个部分:它首先导入相关的Objective-C框架,该框架为AppleScript提供了额外的功能;然后,我定义了实际的处理程序本身,称为JSONtoRecord,我将在下面对其进行描述。最后是脚本的底部,您可以在其中输入代码并对其执行任何您喜欢的操作:

代码语言:javascript
复制
    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"}

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

在这些情况下,它返回的是一个本机JSON对象,所有的AppleScript变量都作为属性值存储在记录中。然后,访问变量就变得非常简单。

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

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

票数 1
EN

Stack Overflow用户

发布于 2018-08-01 21:11:24

简短回答:不幸的是,AppleScript没有提供一个内置的特性来解析类似于JavaScript的JSON.parse()方法的JSON。

下面是几个解决方案:

  • Solution 1:需要安装第三方插件,可能并不总是安装feasible.
  • Solution 2:不需要安装任何第三方插件,而是将内置到macOS中的工具/功能作为标准使用。

解决方案1:

如果你有幸能够在你的用户系统上安装第三方插件,那么你可以安装JSON Helper for AppleScript (正如@user3439894在评论中建议的那样)。

然后在您的AppleScript中使用它,如下所示:

代码语言:javascript
复制
set srcJson to read POSIX file (POSIX path of (path to home folder) & "Desktop/foobar.json")
tell application "JSON Helper" to set myList to read JSON from srcJson

解释:

  1. 在第1行,我们读取.json文件的内容,并将其赋给名为srcJson的变量。

请注意,您需要更改路径部分(即necessary.

  • On __)作为第二行,我们将使用JSON Helper插件解析内容。这会将源JSON数组的每一项分配给一个新的AppleScript list。将生成的AppleScript list赋值给一个名为myList.

的变量

解决方案2:

通过将内置在macOS中的工具作为标准使用,您还可以通过AppleScript执行以下操作。这里假设你的JSON文件是valid,并且只包含一个数组:

代码语言:javascript
复制
set TID to AppleScript's text item delimiters
set AppleScript's text item delimiters to ","
set myList to text items of (do shell script "tr ''\\\\n\\\\r''  ' ' <~/Desktop/foobar.json | sed 's/^ *\\[ *\"//; s/ *\" *\\] *$//; s/\" *, *\"/,/g;'")
set AppleScript's text item delimiters to TID

注意:__:您需要根据需要更改路径部分(即~/Desktop/foobar.json__)。

此外,如果您的.json文件名包含空格,则需要使用\\__对其进行转义。例如~/Desktop/foo\\ bar.json

解释:

第1行AppleScript的当前行被分配给名为TID.

  • On的变量,第2行text item delimiters被设置为逗号-这将有助于从源JSON数组中提取每个单独的值,并将每个值分配给新的
  1. 行3通过do shell script命令执行

脚本,该命令执行以下操作:

代码语言:javascript
复制
- Reads the content of the source `.json` file via the part which reads `~/Desktop/foobar.json`. This path currently assumes the file is named `foobar.json` and resides in your `Desktop` folder _(You'll need to change this path to wherever your actual file exists)_.
- The content of `foobar.json` is redirected, (note the `<` before the filepath), to [`tr`](https://ss64.com/bash/tr.html) (i.e. the part which reads: `tr ''\\\\n\\\\r'' ' '`). This translation will replace any newline characters which may exists in the contents of the source `.json` Array with space characters. This ensures the contents of `foobar.json` is transformed to one line.

备注:JSON数组可以在每一项之间包含换行符,并且仍然有效,所以尽管您问题中给出的示例JSON出现在一行中-但这不是本解决方案的要求,因为它也将处理多行。

-一行文本然后被输送到seds command进行进一步处理(即读作:| sed 's/^ *\\[ *\"//; s/ *\" *\\] *$//; s/\" *, *\"/,/g;'的部分)。

s命令的语法为's/regexp/replacement/flags'

让我们详细分析每个s命令,以进一步了解发生了什么:

代码语言:javascript
复制
    - **`s/^ *\\[ *\"//`** removes the opening square bracket `[`, which may be preceded or followed by zero or more space characters, and the following double quote (i.e. the first occurrence) from the beginning of the string.
    - **`s/ *\" *\\] *$//`** removes the closing square bracket `]`, which may be preceded or followed by zero or more space characters, and the preceding double quote (i.e. the last occurrence) from the end of the string.
    - **`s/\" *, *\"/,/g`** replaces single commas, (which may be preceded with zero or more spaces, and/or followed by zero or more spaces) with a single comma.

代码语言:javascript
复制
- The initial part on _line 3_ which reads; `set myList to text items of ...` utilizes `text items` to read the String into an AppleScript `list` using commas as delimiters to determine each item of the `list`. The resultant Array is assigned to a variable named `myList`.

第4行的

  1. AppleScript's text item delimiters将恢复为其原始值。

使用一个变量作为源JSON文件路径。

如果您想使用一个变量作为源.json文件的文件路径,那么您可以这样做:

代码语言:javascript
复制
set srcFilePath to quoted form of (POSIX path of (path to home folder) & "Desktop/foobar.json")

set TID to AppleScript's text item delimiters
set AppleScript's text item delimiters to ","
set myList to text items of (do shell script "tr ''\\\\n\\\\r'' ' ' <" & srcFilePath & " | sed 's/^ *\\[ *\"//; s/ *\" *\\] *$//; s/\" *, *\"/,/g;'")
set AppleScript's text item delimiters to TID

注释这与第一个示例非常相似。值得注意的区别是:

在第一行,我们将文件路径分配给一个名为srcFilePath.

  • In
  • 的变量,我们引用了do shell script变量。

关于JSON转义特殊字符的补充说明: JSON解决方案2保留了任何可能存在于源数组的值中的JSON escaped special characters。但是,解决方案1将解释它们。

警告JSON解决方案2当源数组中的项包含逗号时会产生意外的结果,因为逗号被用作text item delimiters

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51616761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档