Skip to content

How to deal with data that can be either an array or a single item? #1795

Answered by mikefarah
boydkelly asked this question in Q&A
Discussion options

You must be logged in to vote

You can force elements to be an array, see here: https://mikefarah.gitbook.io/yq/usage/xml#parse-xml-force-as-an-array

The idea is to set the fields to be an empty array concatenated with its current contents.

To convert everything into an array - you could do something like this:

yq '([..] | reverse | .. ) |= [] + .' file.xml -oy 

Explanation

  • [] + . will convert a scalar into an array, and have no affect on arrays - as explained in the doc link above.
  • [..] | reverse | .. is a little funky. In theory you could just do .. to match all elements and pass those through to be updated. But there's an issue in yq if you update a parent first and then a child in the same expression (bug raised…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by boydkelly
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants