gpt4 book ai didi

json - SuperObject - 使用 "."文字解析字段名中的数据

转载 作者:行者123 更新时间:2023-12-03 15:22:26 25 4
gpt4 key购买 nike

我最近在解析 JSON 时遇到了困难。您会看到,在使用 CloudFlare 客户端接口(interface) API 时,我想查找特定 IP 的“威胁评级”。问题是,由于 API 的设计,格式是这样的;

{
response: {
xxx.xxx.xxx.xxx: <value>,
calls_left: 299
},
result: "success",
msg: null
}

xxx.xxx.xxx.xxx代表我需要从中检索数据的字段名称。您可能会立即看到我面临的问题;解析字符串中的点字符被假定为当前路径中的子级别。

<value>代表IP的实际评级。但是,其返回的格式和数据类型有所不同。在不构成威胁或没有威胁评级的 IP 上,它返回 false作为 bool 值。在搜索引擎爬虫上,它返回 "SE:<var>" (其中 <var> 是数值)作为字符串。对于已知威胁,它返回 "BAD:<var>" (其中 <var> 是一个数值)。因此,我不能依赖返回的已知数据类型。

然而,主要问题是,由于字段名称中的点,尝试从此字段读取值显然会失败。

最佳答案

无需黑客攻击。您所需要的只是通过 AsObject。然后使用该名称(包括嵌入的点),而不将其视为路径说明符。

const Line1 = '{'
+ #13#10' response: {'
+ #13#10' xxx.xxx.xxx.xxx: "somestring",'
+ #13#10' calls_left: "299"'
+ #13#10' },'
+ #13#10' result: "success",'
+ #13#10' msg: null'
+ #13#10'}';

var
super: ISuperObject;
res: ISuperObject;
begin
super := SO(Line1);
res := super.O['response'];

writeln('S[calls_left''] on res: ', res.S['calls_left']);
writeln('S[''xxx.xxx.xxx.xxx''] on res: ', res.S['xxx.xxx.xxx.xxx']);

writeln('Names: ', res.AsObject.GetNames.AsString);
writeln('Values: ', res.AsObject.GetValues.AsString);

writeln('S[''xxx.xxx.xxx.xxx''] on res: through AsObject: ',
res.AsObject.S['xxx.xxx.xxx.xxx']);

给出以下结果:

S[calls_left'] on res: 299
S['xxx.xxx.xxx.xxx'] on res:
Names: ["calls_left","xxx.xxx.xxx.xxx"]
Values: ["299","somestring"]
S['xxx.xxx.xxx.xxx'] on res: through AsObject: somestring

关于json - SuperObject - 使用 "."文字解析字段名中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com