如何使用Record将JSON-string转换为Binary? Web.Contents + POST + Power Query

时间:2015-05-11 01:51:26

标签: powerquery

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的方法,它应该是这样的:

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 How to POST a multipart/form-data using Power Query's 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
]

有更好的解决方法吗?

2 个答案:

答案 0 :(得分:2)

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

这不太理想,但您可以像toJson那样推广自己的值到JSON转换函数:

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将使用很多记忆)

答案 1 :(得分:1)

SOME_CONVERTER == Json.FromValue

String uniqueInstalls = obj.getJSONObject("current").getInt("totalUniqueInstall");