Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

json - JQ command to extract names into an array from a String

Input is a document . I will get names in a String preceded by number

 {"doc": [
    {
      "cNo": "6222332 22450 32",
      "cNames": " 1 MANJSY JOAU 2 CHAFANH BINO",
      "cExpiry": "04/2025"
    },
    {
      "fields": 3,
      "documents": 1
    }
  ]}

The expected output is a name array sometime like shown below

 {"doc": [
    {
      "cNo": "6222332 22450 32",
      "cNameArray": [
                       "MANJSY JOAU",
                       "CHAFANH BINO"
                    ],
      "cExpiry": "04/2025"
    },
    {
      "fields": 3,
      "documents": 1
    }
  ]}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The question as I understand it has two main parts:

  1. Converting a string with integer and non-integer segments to an array
  2. Changing the key name from cNames to cNameArray

In the present context, the first part could be accomplished by:

.doc[0] |= (.cNames |= [splits(" *[0-9] *")][1:])

And the second could be accomplished by using with_entries, thus preserving the ordering of the keys:

.doc[0] |= (.cNames |= [splits(" *[0-9] *")][1:]
            | with_entries(if .key == "cNames" 
                           then .key = "cNameArray"
                           else . end) )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...