Skip to content

Latest commit

 

History

History
80 lines (67 loc) · 2.64 KB

Convert a json file to a multi row with a matrix of all the nested objects.md

File metadata and controls

80 lines (67 loc) · 2.64 KB

(jump to the answer)

In order to use the Extended Choice Parameter Jenkins plugin, I need to create a file containing a matrix with several options, such as:

    Country     State   City
    USA         FL      Miami
    USA         FL      Tampa
    USA         FL      Jacksonville
    USA         NY      NYC
    USA         NY      Rochester
    USA         NY      Syracuse

Given this list could be quite a challenge to maintain, I thought of creating a json file, for example (:

["USA":       
 [{        
      "NY": [
            "NYC",
            "Rochester",
            "Syracuse"
    ],
    "FL": [
            "Miami",
            "Tampa",
            "Jacksonville",
   etc...

The question is how to convert a JSON file with many nested objects to a matrix in which the last column is always the deepest nested object?

Alternatively, is there another way to keep the parameters' file maintainable?

I can use bash, python etc...

Thanks!

A:

The JSON above needs to be corrected, as it's invalid. Once corrected, then this is how it looks with jtc:

bash $ <file.json jtc 
{
   "USA": [
      {
         "FL": [
            "Miami",
            "Tampa",
            "Jacksonville"
         ],
         "NY": [
            "NYC",
            "Rochester",
            "Syracuse"
         ]
      }
   ]
}
bash $ 
bash $ <file.json jtc -w' ' -T'"Country\tState\tCity"' -w'[:]<C>k[0][:]<S>k[:]' -qqT'"{C}\t{S}\t{}"'
Country	State	City
USA	FL	Miami
USA	FL	Tampa
USA	FL	Jacksonville
USA	NY	NYC
USA	NY	Rochester
USA	NY	Syracuse
bash $ 

Explanations:

  • here, each template is per each walk, thus first walk -w' ' is dummy - it only facilitates the header template
  • second walk:
    • [:]<C>k : walk each top object and memorize its label (country) into the namespace C
    • [0][:]<S>k: descend into the 1st element (the structure it seems superfluous), then for each iterable (object) memorise its label (state) into the namespace K
    • [:]: iterate over each city
  • template-interpolate country (C), state (S) and city (last walked element - {}) using -T'"{C}\t{S}\t{}"'
  • -qq: drop the outer quotation marks from the result