【问题标题】:How to process null value inside json string using lua?如何使用lua处理json字符串中的空值?
【发布时间】:2019-08-12 16:25:53
【问题描述】:

我在星号 pbx 中使用 lua。处理 json 字符串时遇到以下问题。

json "null" 值在 lua 中转换为函数类型。为什么?

如何处理这种情况?因为我期待 nil 因为在 json 中没有值意味着 null 而 nil 在 lua 中没有任何意义。

local json = require( "json" )
local inspect = require("inspect")
local myjson_str='{"Sms":{"key":"xxxxxxxxxxxxxxxxxxxxx","to":"{caller}","senderid":null,"type":"Simple","content":"Your request has been accepted in Previous Miss call. We get back to you very soon."}}'

local myjson_table = json.decode(myjson_str)
print(type(myjson_table["Sms"]["senderid"]))
print(myjson_table)
print(inspect(myjson_table))
print(json.encode(myjson_table))

上面的输出是

function
table: 0xf5e770
{
  Sms = {
    content = "Your request has been accepted in Previous Miss call. We get back to you very soon.",
    key = "xxxxxxxxxxxxxxxxxxxxx",
    senderid = <function 1>,
    to = "{caller}",
    type = "Simple"
  }
}
{"Sms":{"type":"Simple","key":"xxxxxxxxxxxxxxxxxxxxx","senderid":null,"content":"Your request has been accepted in Previous Miss call. We get back to you very soon.","to":"{caller}"}}

【问题讨论】:

    标签: json lua


    【解决方案1】:

    由特定库决定如何表示null 值。 使用nil 有其自身的问题,因为它也无法找到 原始 JSON 的键为空值,或者根本没有这样的键。 所以一些库只是返回一些独特的价值。有些提供 一种传递此值的方法,例如json.deconde(str, NULL_VALUE)。 所以答案就是阅读您使用的库的文档/源代码。 它很可能会提供类似json.null 的值来检查 任一值为空。但是功能真的是很奇怪的选择,因为 它们有一些不确定的唯一性规则。 或者尝试其他库。

    【讨论】:

    • json.util.null 是我最终找到的函数。我设法处理相同的。您的观点是正确的,这取决于您使用的库/语言。
    【解决方案2】:

    首先,@moteus 是对的:

    由特定库决定如何表示空值

    如果您使用JSON library by Jeffrey Friedl,解决方案是使用占位符而不是null,并使用指定的编码选项将表结构序列化为json字符串:

    -- define a placeholder
    NullPlaceholder = "\0"
    
    -- use it in an internal table
    tableStructure = {}
    tableStructure['someNullValue'] = NullPlaceholder
    
    -- pass the placeholder to the encode methode
    encode_options = { null = NullPlaceholder }
    jsonString = JSON:encode(tableStructure, nil, encode_options)
    

    导致

    {"someNullValue": null}
    

    【讨论】:

      猜你喜欢
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2010-09-28
      • 1970-01-01
      相关资源
      最近更新 更多