如何使用记录将 JSON-string 转换为二进制? Web.Contents + POST + 电源查询

How to convert JSON-string to Binary using a Record? Web.Contents + POST + Power Query

Web.Contents 方法将内容作为二进制文件

我用这个代码。有效

query = "{
    ""field1"" : ""value1"",
    ""field2"" : ""value2"",
    ""field3"" : {
        ""sub_field_3_1"" : [""value_3_1_1"", ""value_3_1_2"", ""value_3_1_1""],
        ""sub_field_3_2"" : [""value_3_2_1"", ""value_3_2_2"", ""value_3_2_1""]
        }
    }",

content = Text.ToBinary(query),

Web.Contents("https://my_url", [
    Headers = [#"Content-Type"="text/xml; charset=utf-8"],
    Content=content
])

我明白,这不是一个好的解决方法,因为没有理由进行双重转换。但是我找不到如何应用记录的方法,它应该是这样的:

record = [
    field1 = value1,
    field2 = value2,
    field3 = [
        sub_field_3_1 = {value_3_1_1, value_3_1_2, value_3_1_1},
        sub_field_3_2 = {value_3_2_1, value_3_2_2, value_3_2_1}
    ]
],

content = SOME_CONVERTER(record),

Web.Contents("https://my_url", [
    Headers = [#"Content-Type"="text/xml; charset=utf-8"],
    Content = content
])

尝试使用 Uri.BuildQueryString () 但它没有正确形成二进制文件

record = [
    field1 = value1,
    field2 = value2,
    field3 = [
        sub_field_3_1 = {value_3_1_1, value_3_1_2, value_3_1_1},
        sub_field_3_2 = {value_3_2_1, value_3_2_2, value_3_2_1}
    ]
],

content = Text.ToBinary(Uri.BuildQueryString(record)),

Web.Contents("https://my_url", [
    Headers = [#"Content-Type"="text/xml; charset=utf-8"],
    Content=content
]

是否有更好的解决方法?

目前,您的硬编码 JSON 字符串是更好的解决方案之一。

它不太理想,但您可以使用自己的值到 JSON 转换函数,例如 toJson:

let
    record = [
        field1 = "value1",
        field2 = "value2",
        field3 = [
            sub_field_3_1 = {"value_3_1_1", null, 3.2},
            sub_field_3_2 = {"value_3_2_1", "value_3_2_2", "value_3_2_1"}
        ]
    ],

    toJson = (v as any) as text =>
      if v is null then "null" else 
      if v is logical or v is number then Text.From(v) else
      if v is text then """" & Text.Replace(Text.Replace(v, "\", "\"), """", "\""") & """" else
      if v is list then "[" & Text.Combine(List.Transform(v, @toJson), ", ") & "]" else
      if v is record then "{" & 
        Text.Combine(List.Transform(
          Record.FieldNames(v),
          (n) => @toJson(n) & ": " & @toJson(Record.Field(v, n))), ", ")
        & "}" else
      error "not implemented",  

    jsonText = toJson(record)
in
    jsonText

与真正的 Json.FromValue 库函数相比,存在一些不足:

  • 只有原始文本转义
    • 请参阅 json.org 了解您需要转义的所有特殊字符
  • 不处理循环 M 值、特殊非数字或其他类型的值类型
  • 会阻塞非常大的值(字符串连接会占用大量内存)

SOME_CONVERTER == Json.FromValue

let
    record = [
        field1 = "value1",
        field2 = "value2",
        field3 = [
            sub_field_3_1 = {"value_3_1_1", "value_3_1_2", "value_3_1_1"},
            sub_field_3_2 = {"value_3_2_1", "value_3_2_2", "value_3_2_1"}
        ]
    ],
    content = Json.FromValue(record),
    web=Web.Contents("https://my_url", [
        Headers = [#"Content-Type"="text/xml; charset=utf-8"],
        Content = content
    ])
in
    web