You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AppleScript字符串转列表及Shell脚本返回列表处理问题

Fixing the Single-Item Menu Issue in Your AppleScript

Got it, let's tackle why your choose from list is displaying that whole {"tacos","burritos"} string as a single option instead of separate items. The problem is simple: when you pull that data via do shell script, you're getting a text representation of a list, not an actual AppleScript list that the choose from list command can work with. We just need to convert that string into a proper list first.

Here's the revised code with step-by-step fixes:

-- Replace this with your actual CSV file path
set csvPath to "/Users/you/Documents/your_menu.csv"
set targetId to "01" -- Using "01" instead of 01 avoids shell parsing weirdness

-- Grab the raw list string from the CSV
set rawMenuText to do shell script "grep " & quoted form of targetId & " " & quoted form of csvPath & " | cut -d ',' -f 2"

-- Convert the text string to an AppleScript list
-- First, strip off the outer curly braces: {"tacos","burritos"} → "tacos","burritos"
set cleanedMenuText to text 2 thru -2 of rawMenuText

-- Set delimiters to split on both ", " (with space) and "," (no space)
-- This also automatically removes the quote marks around each item
set AppleScript's text item delimiters to {""", """, ""","""}
set myMenu to text items of cleanedMenuText
-- Always reset delimiters to default when done!
set AppleScript's text item delimiters to ""

-- Now use the proper list in your menu
set menuChoice to choose from list myMenu with prompt "Pick your favorite:"
if menuChoice is not false then -- Handle the case where user clicks Cancel
    display alert "You selected: " & item 1 of menuChoice
end if

What Changed & Why:

  • Quoted Form: Wrapping targetId and csvPath in quoted form of prevents shell errors if your path or ID has spaces, special characters, or numbers that the shell might misinterpret.
  • Stripping Curly Braces: text 2 thru -2 cuts off the first { and last } from the raw string, leaving us with just the quoted items separated by commas.
  • Smart Delimiters: By setting delimiters to both ", " and ",", we split the string correctly regardless of whether there's a space after the comma in your CSV. This also strips the quote marks from each item automatically.
  • Cancel Handling: Added a check so the script doesn't crash if the user clicks Cancel instead of selecting an item.

Quick Note for Edge Cases:

If your menu items ever include commas inside them (unlikely in your example), you'd need a more robust CSV parser. But for the format you shared—items wrapped in quotes inside curly braces—this solution works perfectly.

内容的提问来源于stack exchange,提问作者Er Ar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:21:22