3

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如何使用 Power Query 的 Web.Contents 发布多部分/表单数据),但它不能正确形成二进制

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
]

有更好的解决方法吗?

4

2 回答 2

2

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

它不太理想,但您可以滚动自己的 value-to-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 值、特殊非数字或其他类型的值类型
  • 会因非常大的值而窒息(字符串 concat 将使用大量内存)
于 2015-05-12T01:47:24.790 回答
1

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
于 2016-10-30T05:19:21.893 回答