"$response"
:
[{"word":"world","phonetic":"/wɝld/","phonetics":[{"text":"/wɝld/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/world-ca.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=238003","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}},{"text":"/wɵːld/","audio":""},{"text":"/wɜːld/","audio":""},{"text":"/wɝld/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/world-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=67249678","license":{"name":"BY-SA 4.0","url":"https://creativecommons.org/licenses/by-sa/4.0"}}],"meanings":[{"partOfSpeech":"noun","definitions":[{"definition":"(with \"the\") Human collective existence; existence in general.","synonyms":[],"antonyms":[],"example":"There will always be lovers, till the world's end."},{"definition":"The Universe.","synonyms":[],"antonyms":[]},{"definition":"(with \"the\") The Earth.","synonyms":[],"antonyms":[],"example":"People are dying of starvation all over the world."},{"definition":"A planet, especially one which is inhabited or inhabitable.","synonyms":[],"antonyms":[],"example":"Our mission is to travel the galaxy and find new worlds."},{"definition":"A very large extent of country.","synonyms":[],"antonyms":[]},{"definition":"(speculation) A realm, such as planet, containing one or multiple societies of beings, especially intelligent ones.","synonyms":[],"antonyms":[],"example":"the world of Narnia; the Wizarding World of Harry Potter; a zombie world"},{"definition":"An individual or group perspective or social setting.","synonyms":[],"antonyms":[],"example":"In the world of boxing, good diet is all-important."},{"definition":"The part of an operating system distributed with the kernel, consisting of the shell and other programs.","synonyms":[],"antonyms":[]},{"definition":"A subdivision of a game, consisting of a series of stages or levels that usually share a similar environment or theme.","synonyms":[],"antonyms":[],"example":"Have you reached the boss at the end of the ice world?"},{"definition":"The twenty-second trump or major arcana card of the tarot.","synonyms":[],"antonyms":[]},{"definition":"A great amount.","synonyms":[],"antonyms":[],"example":"Taking a break from work seems to have done her a world of good."},{"definition":"Age, era","synonyms":[],"antonyms":[]}],"synonyms":["planet","circle","Earth","Sol III","globe"],"antonyms":[]},{"partOfSpeech":"verb","definitions":[{"definition":"To consider or cause to be considered from a global perspective; to consider as a global whole, rather than making or focussing on national or other distinctions; compare globalise.","synonyms":[],"antonyms":[]},{"definition":"To make real; to make worldly.","synonyms":[],"antonyms":[]}],"synonyms":[],"antonyms":[]}],"license":{"name":"CC BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"},"sourceUrls":["https://en.wiktionary.org/wiki/world"]}]
^ обратите внимание definition":"(with \"the\"
<--- кавычки экранированы
echo "$response" | jq -c '.[].meanings[]' | while read meaning; do
echo "$meaning"
echo "$meaning" | jq -r '.'
exit
done
^ возвращает:
{"partOfSpeech":"noun","definitions":[{"definition":"(with "the") Human collective existence; existence in general.","synonyms":[],"antonyms":[],"example":"There will always be lovers, till the world's end."},{"definition":"The Universe.","synonyms":[],"antonyms":[]},{"definition":"(with "the") The Earth.","synonyms":[],"antonyms":[],"example":"People are dying of starvation all over the world."},{"definition":"A planet, especially one which is inhabited or inhabitable.","synonyms":[],"antonyms":[],"example":"Our mission is to travel the galaxy and find new worlds."},{"definition":"A very large extent of country.","synonyms":[],"antonyms":[]},{"definition":"(speculation) A realm, such as planet, containing one or multiple societies of beings, especially intelligent ones.","synonyms":[],"antonyms":[],"example":"the world of Narnia; the Wizarding World of Harry Potter; a zombie world"},{"definition":"An individual or group perspective or social setting.","synonyms":[],"antonyms":[],"example":"In the world of boxing, good diet is all-important."},{"definition":"The part of an operating system distributed with the kernel, consisting of the shell and other programs.","synonyms":[],"antonyms":[]},{"definition":"A subdivision of a game, consisting of a series of stages or levels that usually share a similar environment or theme.","synonyms":[],"antonyms":[],"example":"Have you reached the boss at the end of the ice world?"},{"definition":"The twenty-second trump or major arcana card of the tarot.","synonyms":[],"antonyms":[]},{"definition":"A great amount.","synonyms":[],"antonyms":[],"example":"Taking a break from work seems to have done her a world of good."},{"definition":"Age, era","synonyms":[],"antonyms":[]}],"synonyms":["planet","circle","Earth","Sol III","globe"],"antonyms":[]}
jq: parse error: Invalid literal at line 1, column 64
Экранирование кавычек исчезло, и jq
не удается проанализировать.
Я пробовал добавлять флаги для эха (-n
и -e
), но это не помогло.
(...также, если вы хотите установить какие-либо переменные внутри цикла while read
, которые сохраняются после выхода из цикла, или если вы ожидаете, что exit
выйдет из сценария целиком, а не только из цикла, обратите внимание на BashFAQ #24 в целом while IFS= read -r meaning; do ...; done < <(jq -c '.[].meanings[]' <<<"$response")
— более надежный код)
... имейте в виду, если вы действительно хотите прочитать только первое значение, а не перебирать остальные (как подразумевает exit
), вы можете просто написать IFS= read -r meaning < <(jq -c '.[].meanings[]' <<<"$response")
и вообще не использовать какой-либо цикл while
.
(кстати, чтобы понять, почему ни один из моих примеров выше не использует echo
вообще, см. отличный ответ на Unix & Linux на Почему printf лучше, чем echo? Стефана Шазеласа, подробно описывающего, почему поведение echo
ненадежно и удивительно).
Спасибо за столько информации, сейчас прочту!
обратите внимание
definition":"(with \"the\"
<--- кавычки экранированы
Используйте read -r
:
while read -r meaning; do …
Смотрите man bash
на read
:
-r Backslash does not act as an escape character. The backslash
is considered to be part of the line. In particular, a
backslash-newline pair may not then be used as a line
continuation.
Спасибо! Я потратил на это пару часов...
@sloppy К вашему сведению, оболочка говорит: «SC2162 (информация): чтение без -r приведет к искажению обратной косой черты».
Между прочим, простого добавления
-r
недостаточно, чтобы полностью запретитьread
изменять содержимое по пути — сделайте этоwhile IFS= read -r meaning
, чтобы избежать обрезки начальных и конечных пробелов. См. BashFAQ #1, где подробно описаны соответствующие передовые практики.