Forum Discussion

kp_pbi's avatar
kp_pbi
Frequent Visitor
8 years ago
Solved

Counter which adds +1 in Table.ExpandListColumn

Hi, I'm using PBI Desktop, and am parsing a JSON field into columns. I'm using the "Transform -> Parse ->JSON", function in Power BI. When i view the "Advanced Editor", the query looks like this:  ...
  • MarcelBeug's avatar
    8 years ago

    Your explanation raises some question marks with me, especially the statement that #"Expanded Rows1" would expand nested records into new rows: if a column with nested records is expanded, the number of rows will not change.

     

    Anyhow, if  I interpret your data structure correctly, then the "Added Index" step in the query below is what you are looking for (you may need to adjust the field names to your actual field names).

     

    let
        #"Parsed JSON" = #table(type table[name = number, job = number, rows = list],
                        {{1,1,{[location = {[loc = "A"],[loc = "B"],[loc = "C"]}]}},
                         {2,2,{[location = {[loc = "A"],[loc = "D"],[loc = "G"]}]}},
                         {3,3,{[location = {[loc = "D"],[loc = "H"],[loc = "Z"]}]}}}),
        #"Expanded rows" = Table.ExpandListColumn(#"Parsed JSON", "rows"),
        #"Expanded rows1" = Table.ExpandRecordColumn(#"Expanded rows", "rows", {"location"}, {"location"}),
    
    /* Column "location" has now nested lists, each containing a number of records (3).
       The step below adds the field Index to each of those records:
    
       In the inner List.Transform, the Index numbers are created {1..List.Count(_)} and converted to records.
    
       After List.Zip this looks like: 
        {{[loc = "A"], [Index = 1]},{[loc = "B"], [Index = 2]},{[loc = "C"], [Index = 3]}}
       so a list in which each element has 2 separate records, each with 1 field.
    
       This list is transformed into a list of single records _{0}&_{1}, each with 2 fields: 
        {[loc = "A", Index = 1],[loc = "B", Index = 2],[loc = "C", Index = 3]} 
    
     */
    
    
        #"Added Index" = 
            Table.TransformColumns(
                #"Expanded rows1",
                {{"location", 
                  each List.Transform(
                            List.Zip({_,
                                        List.Transform(
                                            {1..List.Count(_)},
                                            each [Index = _])}),
                            each _{0}&_{1}),
                  type list}}),
        #"Expanded location" = Table.ExpandListColumn(#"Added Index", "location"),
        #"Expanded location1" = Table.ExpandRecordColumn(#"Expanded location", "location", {"loc", "Index"}, {"loc", "Index"})
    in
        #"Expanded location1"