代码之家  ›  专栏  ›  技术社区  ›  David542

JSON中的数字排序

  •  1
  • David542  · 技术社区  · 1 年前

    我想排序 JSON 字段的数值。以下是一个示例:

    with tbl as (
      select json '1' j union all
      select json '2' j union all
      select json '"hello"' union all
      select json '"alpha"' union all
      select json '[1,2,3]'
    ) select j from tbl order by Float64(j)
    

    然而,这给了我一个错误(显然):

    提供的JSON输入不是数字;FLOAT64表达式中有错误

    我当然知道,但我想看到的结果更像 TRY_CAST ,即:将所有非数值视为 null 。这样做的正确方法是什么?在我写这篇文章的时候,一个选择是绕 TO_JSON_STRING 铸造,然后应用 TRY_CAST 关于这一点。例如:

    with tbl as (
      select json '1' j union all
      select json '2' j union all
      select json '"hello"' union all
      select json '"alpha"' union all
      select json '[1,2,3]'
    ) select SAFE_CAST(to_json_string(j) as float64) from tbl
    

    这是唯一的方法吗?

    1 回复  |  直到 1 年前
        1
  •  2
  •   Jaytiger    1 年前

    你也可以试试这个。

    with tbl as (
      select json '1' j union all
      select json '2' j union all
      select json '"hello"' union all
      select json '"alpha"' union all
      select json '[1,2,3]'
    )
    select SAFE.FLOAT64(j) from tbl;
    

    查询结果

    enter image description here