Можно ли преобразовать JSON или YAML в XML с помощью jq/yq/xq
Мне удалось успешно преобразовать файл в файл, используя
Возможно ли с помощью следующих инструментовjq
,yq
,xq
, чтобы преобразовать из любогоYAML
или вернуться к формату?
Вот пример моего файла примера:
{
"security-settings": {
"@xmlns": "urn:activemq:core",
"security-setting": {
"@match": "#",
"permission": [
{
"@type": "createNonDurableQueue",
"@roles": "admins"
},
{
"@type": "deleteNonDurableQueue",
"@roles": "admins"
},
{
"@type": "manage",
"@roles": "admins"
}
]
}
}
}
Спасибо любезно за любую помощь или предложение.
Дополнительная информация:
Исходный XML, который я первоначально использовал, выглядит следующим образом:
<?xml version="1.0"?>
<security-settings xmlns="urn:activemq:core">
<security-setting match="#">
<permission type="createNonDurableQueue" roles="admins"/>
<permission type="deleteNonDurableQueue" roles="admins"/>
<permission type="createDurableQueue" roles="admins"/>
<permission type="deleteDurableQueue" roles="admins"/>
<permission type="createAddress" roles="admins"/>
<permission type="deleteAddress" roles="admins"/>
<permission type="consume" roles="admins"/>
<permission type="browse" roles="admins"/>
<permission type="send" roles="admins"/>
<permission type="manage" roles="admins"/>
</security-setting>
</security-settings>
Прямое преобразование из в с помощью командыxq -yY < security-settings.xml
сгенерировал вывод:
{
"security-settings": {
"@xmlns": "urn:activemq:core",
"security-setting": {
"@match": "#",
"permission": [
{
"@type": "createNonDurableQueue",
"@roles": "admins"
},
{
"@type": "deleteNonDurableQueue",
"@roles": "admins"
},
{
"@type": "createDurableQueue",
"@roles": "admins"
},
{
"@type": "deleteDurableQueue",
"@roles": "admins"
},
{
"@type": "createAddress",
"@roles": "admins"
},
{
"@type": "deleteAddress",
"@roles": "admins"
},
{
"@type": "consume",
"@roles": "admins"
},
{
"@type": "browse",
"@roles": "admins"
},
{
"@type": "send",
"@roles": "admins"
},
{
"@type": "manage",
"@roles": "admins"
}
]
}
}
}
Собственное преобразование, предложенное при запускеyq -o=xml -P json_file
для обратного преобразования изJSON
to to не дает того же результата, что и источникXML
как показано ранее.
<security-settings>
<@xmlns>urn:activemq:core</@xmlns>
<security-setting>
<@match>#</@match>
<permission>
<@type>createNonDurableQueue</@type>
<@roles>admins</@roles>
</permission>
<permission>
<@type>deleteNonDurableQueue</@type>
<@roles>admins</@roles>
</permission>
<permission>
<@type>createDurableQueue</@type>
<@roles>admins</@roles>
</permission>
<permission>
<@type>deleteDurableQueue</@type>
<@roles>admins</@roles>
</permission>
<permission>
<@type>createAddress</@type>
<@roles>admins</@roles>
</permission>
<permission>
<@type>deleteAddress</@type>
<@roles>admins</@roles>
</permission>
<permission>
<@type>consume</@type>
<@roles>admins</@roles>
</permission>
<permission>
<@type>browse</@type>
<@roles>admins</@roles>
</permission>
<permission>
<@type>send</@type>
<@roles>admins</@roles>
</permission>
<permission>
<@type>manage</@type>
<@roles>admins</@roles>
</permission>
</security-setting>
</security-settings>
Я работаю на виртуальной машине Fedora 36, и это yq, который я установил на коробке.
yq --version
yq 3.0.2
yq --help
usage: yq [options] <jq filter> [input file...]
yq: Command-line YAML processor - jq wrapper for YAML documents
yq transcodes YAML documents to JSON and passes them to jq.
See https://github.com/kislyuk/yq for more information.
positional arguments:
jq_filter
files
options:
-h, --help show this help message and exit
--yaml-output, --yml-output, -y
Transcode jq JSON output back into YAML and emit it
--yaml-roundtrip, --yml-roundtrip, -Y
Transcode jq JSON output back into YAML and emit it. Preserve YAML tags and styles by representing them as extra items in their enclosing mappings and sequences while in JSON. This option is incompatible with jq filters that do not expect these extra items.
--width WIDTH, -w WIDTH
When using --yaml-output, specify string wrap width
--indentless-lists, --indentless
When using --yaml-output, indent block style lists (sequences) with 0 spaces instead of 2
--in-place, -i Edit files in place (no backup - use caution)
--version show program's version number and exit
jq - commandline JSON processor [version 1.6]
Usage: jq [options] <jq filter> [file...]
jq [options] --args <jq filter> [strings...]
jq [options] --jsonargs <jq filter> [JSON_TEXTS...]
jq is a tool for processing JSON inputs, applying the given filter to
its JSON text inputs and producing the filter's results as JSON on
standard output.
The simplest filter is ., which copies jq's input to its output
unmodified (except for formatting, but note that IEEE754 is used
for number representation internally, with all that that implies).
For more advanced filters see the jq(1) manpage ("man jq")
and/or https://stedolan.github.io/jq
Example:
$ echo '{"foo": 0}' | jq .
{
"foo": 0
}
Some of the options include:
-c compact instead of pretty-printed output;
-n use `null` as the single input value;
-e set the exit status code based on the output;
-s read (slurp) all inputs into an array; apply filter to it;
-r output raw strings, not JSON texts;
-R read raw strings, not JSON texts;
-C colorize JSON;
-M monochrome (don't colorize JSON);
-S sort keys of objects on output;
--tab use tabs for indentation;
--arg a v set variable $a to value <v>;
--argjson a v set variable $a to JSON value <v>;
--slurpfile a f set variable $a to an array of JSON texts read from <f>;
--rawfile a f set variable $a to a string consisting of the contents of <f>;
--args remaining arguments are string arguments, not files;
--jsonargs remaining arguments are JSON arguments, not files;
-- terminates argument processing;
Named arguments are also available as $ARGS.named[], while
positional arguments are available as $ARGS.positional[].
See the manpage for more options.
@ikegami
Вот результат:
эхо <ele attr_name="attr_value">ele_value</ele> | xq
{
"ele": {
"@attr_name": "attr_value",
"#text": "ele_value"
}
}
эхо <ele attr_name="attr_value">ele_value</ele> | хд | ./yq_linux_amd64 -o=xml -P
<ele>
<@attr_name>attr_value</@attr_name>
<#text>ele_value</#text>
</ele>
1 ответ
Во-первых, получить версию
yq
из этого репозитория github : https://github.com/mikefarah/yq/releases/download/v4.26.1/yq_linux_amd64
Он предоставляет флаги/функции, которые другие могут не поддерживать.
Затем можно использовать следующую команду для регенерации XML:
./yq_linux_amd64 \
--xml-attribute-prefix @ \
--xml-content-name '#text' \
--input-format yaml \
--output-format xml \
security-settings.yaml
Та же самая команда работает и для входных данных JSON, поскольку JSON является подмножеством YAML.