Как вставить поля в файл JSON, используя jq? - PullRequest
0 голосов
/ 07 июня 2018

Допустим, у меня есть файл JSON recipe.json, содержащий это:

{
            "name": "Curried Lentils and Rice",
            "ingredients": [
                {
                    "quantity": "1 quart",
                    "name": "beef broth",
                    "type": "Misc"
                },
                {
                    "quantity": "1 cup",
                    "name": "dried green lentils",
                    "type": "Misc"
                },
                {
                    "quantity": "1/2 cup",
                    "name": "basmati rice",
                    "type": "Misc"
                },
                {
                    "quantity": "1 tsp",
                    "name": "curry powder",
                    "type": "Condiments"
                },
                {
                    "quantity": "1 tsp",
                    "name": "salt",
                    "type": "Condiments"
                }
            ],
            "steps": [
                "Bring broth to a low boil.",
                "Add curry powder and salt.",
                "Cook lentils for 20 minutes.",
                "Add rice and simmer for 20 minutes.",
                "Enjoy!"
            ],
            "timers": [
                0,
                0,
                20,
                20,
                0
            ],
            "imageURL": "http://dagzhsfg97k4.cloudfront.net/wp-content/uploads/2012/05/lentils3.jpg"
}

И я пытаюсь вставить новые поля JSON в файл в определенных местах в файлес помощью jq , такой как:

"cuisine": "meditaranean"

, станет 2-я запись, а

"meal": "lunch"

станет 4-я запись.Таким образом, файл после команды выглядит следующим образом:

{
            "name": "Curried Lentils and Rice",
            "cuisine": "meditaranean"
            "ingredients": [
                {
                    "quantity": "1 quart",
                    "name": "beef broth",
                    "type": "Misc"
                },
                {
                    "quantity": "1 cup",
                    "name": "dried green lentils",
                    "type": "Misc"
                },
                {
                    "quantity": "1/2 cup",
                    "name": "basmati rice",
                    "type": "Misc"
                },
                {
                    "quantity": "1 tsp",
                    "name": "curry powder",
                    "type": "Condiments"
                },
                {
                    "quantity": "1 tsp",
                    "name": "salt",
                    "type": "Condiments"
                }
            ],
            "meal": "lunch"
            "steps": [
                "Bring broth to a low boil.",
                "Add curry powder and salt.",
                "Cook lentils for 20 minutes.",
                "Add rice and simmer for 20 minutes.",
                "Enjoy!"
            ],
            "timers": [
                0,
                0,
                20,
                20,
                0
            ],
            "imageURL": "http://dagzhsfg97k4.cloudfront.net/wp-content/uploads/2012/05/lentils3.jpg"
}

Мой вопрос заключается в том, как сделать это с помощью jq ?

Примечание. Этот другой вопрос адресовано выполнение обновлений отдельных полей, в то время как текущий вопрос о вставках.Они такие же разные, как оранжевые и желтые болгарские перцы, что отличается!(Не заставляйте меня добавлять изображение сладкого перца к этому сообщению, клянусь, я сделаю это, если придется.)

Ответы [ 2 ]

0 голосов
/ 23 апреля 2019

Там, где ваш json сохранен в foods.json, выполнение следующей команды приведет к тому, что вам нужно.

jq '.cusine="mediteranean"' meals.json
0 голосов
/ 07 июня 2018

С помощью вспомогательной функции задача становится тривиальной:

def insert_kv($key; $value; $ix):
  to_entries
  | .[0:$ix] + [{key: $key, value: $value}] + .[$ix:]
  | from_entries;

insert_kv("cuisine"; "mediterranean"; 1)
| insert_kv("meal"; "lunch"; 3)

Вы можете (альтернативно или дополнительно) определить:

def insert_kv($object; $ix):
  to_entries
  | .[0:$ix] + ($object|to_entries) + .[$ix:]
  | from_entries;
...