Цикл while удаляет кавычки, из-за чего jq не может проанализировать json

"$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), но это не помогло.

Между прочим, простого добавления -r недостаточно, чтобы полностью запретить read изменять содержимое по пути — сделайте это while IFS= read -r meaning, чтобы избежать обрезки начальных и конечных пробелов. См. BashFAQ #1, где подробно описаны соответствующие передовые практики.

Charles Duffy 29.07.2024 20:50

(...также, если вы хотите установить какие-либо переменные внутри цикла while read, которые сохраняются после выхода из цикла, или если вы ожидаете, что exit выйдет из сценария целиком, а не только из цикла, обратите внимание на BashFAQ #24 в целом while IFS= read -r meaning; do ...; done < <(jq -c '.[].meanings[]' <<<"$response") — более надежный код)

Charles Duffy 29.07.2024 20:52

... имейте в виду, если вы действительно хотите прочитать только первое значение, а не перебирать остальные (как подразумевает exit), вы можете просто написать IFS= read -r meaning < <(jq -c '.[].meanings[]' <<<"$response") и вообще не использовать какой-либо цикл while.

Charles Duffy 29.07.2024 20:56

(кстати, чтобы понять, почему ни один из моих примеров выше не использует echo вообще, см. отличный ответ на Unix & Linux на Почему printf лучше, чем echo? Стефана Шазеласа, подробно описывающего, почему поведение echo ненадежно и удивительно).

Charles Duffy 29.07.2024 20:58

Спасибо за столько информации, сейчас прочту!

sloppy 29.07.2024 21:05
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
5
50
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

обратите внимание 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 29.07.2024 20:50

@sloppy К вашему сведению, оболочка говорит: «SC2162 (информация): чтение без -r приведет к искажению обратной косой черты».

that other guy 30.07.2024 18:44

Другие вопросы по теме