Quantcast
Channel: SQL Server
Viewing all articles
Browse latest Browse all 3819

Blog Post: Generating JSON In Power BI And Power Query

$
0
0
Often, when calling web services from Power BI or Power Query, you’ll need to generate some JSON inside your query to send to these web services. The M language makes this relatively easy to do with the Json.FromValue() function but there’s only one example of how to use it in the help so I though it might be useful to provide some worked examples of M data types and how Json.FromValue() turns them into JSON. First, here’s a function – that I’ve called GetJson() for the examples here – that takes a parameter of any data type, passes it to Json.FromValue() and returns the JSON representation of the input as text: (InputData) => let JsonOutput = Json.FromValue(InputData), OutputText = Text.FromBinary(JsonOutput) in OutputText Now, let’s see what this returns for a variety of different data types. Tables Take the following table on an Excel worksheet, called “Sales”: The following query loads the data from this table and calls the GetJson() function defined above: let Source = Excel.CurrentWorkbook(){[Name="Sales"]}[Content], #"Changed Type" = Table.TransformColumnTypes( Source, {{"Month", type text}, {"Sales", Int64.Type}}), Output = GetJson(#"Changed Type") in Output It returns the following JSON, an array of objects: [ {"Month":"January","Sales":1}, {"Month":"February","Sales":2}, {"Month":"March","Sales":3} ] Lists M language lists are represented as JSON arrays, so the following query: GetJson({"Apples", "Oranges", "Pears"}) …returns ["Apples","Oranges","Pears"] And GetJson({{1,"Apples"}, {2,"Oranges"}, {3,"Pears"}}) …returns [[1,"Apples"],[2,"Oranges"],[3,"Pears"]] Records M language records are represented as JSON objects, so: GetJson([month="January", product="Apples", sales=1]) …returns {"month":"January","product":"Apples","sales":1} Nested Data Finally, in M it’s possible to have nested data structures: lists of tables, records containing lists and so on. These can be converted to JSON too, so in the following example of a record containing a text value, a list and a table ( created using #table ): GetJson( [ product="Apples", colours={"Red","Green"}, sales= #table({"Month", "Sales"}, { {"January", 1}, {"February", 2} } ) ] ) …the JSON output is: { "product":"Apples", "colours":[ "Red", "Green" ], "sales":[ { "Month":"January", "Sales":1 }, { "Month":"February", "Sales":2 } ] } You can download the sample Excel 2016 workbook with these examples in here .

Viewing all articles
Browse latest Browse all 3819

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>