Forum Discussion

al358's avatar
al358
Frequent Visitor
4 years ago
Solved

Look up values from disordered JSON objects and place in correct columns

In Power BI I have a column containing JSON. Each row contains 3 key:value pairs in the format of 3-digits:4-digits as in the below example   Table 1 {"567":"1259","568":"1535","570":"1264"} {"393...
  • mahoneypat's avatar
    4 years ago

    Here's one way to do it in the query editor.  To see how it works, just create a blank query, open the Advanced Editor and replace the text there with the M code below.

     

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("NcvLEYAgDEXRXt6aheSHsRVCJY69C0G3Z+7tHXdArQWuQCX1QFlwblDWDe34CpPAg1FyZOdkV6rZsVPC/H6QBLFVzHG8", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [JsonData = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"JsonData", type text}}),
        #"Added Custom1" = Table.AddColumn(#"Changed Type", "Result", each let 
    thisrecord = Json.Document([JsonData]),
    sortedrecord = Record.ReorderFields(thisrecord, List.Sort(Record.FieldNames(thisrecord))),
    renamedrecord = Record.RenameFields(sortedrecord, List.Zip({Record.FieldNames(sortedrecord), {"Fruit", "Size", "Color"}}))
    in 
    renamedrecord),
        #"Expanded Result" = Table.ExpandRecordColumn(#"Added Custom1", "Result", {"Fruit", "Size", "Color"}, {"Fruit", "Size", "Color"})
    in
        #"Expanded Result"

     

    The key step is the custom column with this expression. Replace [JsonData] with your actual column name with the Json string.

     

    let
    thisrecord = Json.Document([JsonData]),
    sortedrecord = Record.ReorderFields(thisrecord, List.Sort(Record.FieldNames(thisrecord))),
    renamedrecord = Record.RenameFields(sortedrecord, List.Zip({Record.FieldNames(sortedrecord), {"Fruit", "Size", "Color"}}))
    in
    renamedrecord

     

    Pat