gpt4 book ai didi

c - 使用C语言解析JSON

转载 作者:行者123 更新时间:2023-11-30 20:30:11 28 4
gpt4 key购买 nike

我知道这是一个看似简单的主题,已经被讨论了一百万次,但我非常坚持遵循其他示例。但我很难遵循网上的大量示例,并且我已经看过其中的很多示例。我目前有一个 JSON 文件,我试图从中提取“价格”值,但我尝试遵循的每个示例都陷入困境和困惑,所以这是我最后的手段。

{"success":true,"errors":[],"results":[{"productConditionId":3442759,"price":169.54,"lowestRange":155.00,"highestRange":229.95}]}

JSON FILE IMAGE

我希望能够将价格“168.54”作为可以分配给变量的整数。

最佳答案

检查卡住库https://github.com/cesanta/frozen体积小、便携且无依赖性。

对于您的情况,解决方案如下:

#include <stdio.h>

#include "frozen.c"

static void scan_array(const char *str, int len, void *user_data) {
struct json_token t;
int i;
float price;
int casted;

printf("Parsing array: %.*s\n", len, str);
for (i = 0; json_scanf_array_elem(str, len, "", i, &t) > 0; i++) {
printf("Index %d, token %.*s\n", i, t.len, t.ptr);
json_scanf(t.ptr, t.len, "{price: %f}", &price);
casted = (int)price;
printf("Price %.2f : price casted %d \n", price, casted);

}
}

int main(void) {

const char *str =
"{\"success\":true,\"errors\":[],\"results\":[{\"productConditionId\":3442759,\"price\":169.54,\"lowestRange\":155.00,\"highestRange\":229.95}]}";

printf("Parsing %s \n", str);
json_scanf(str, strlen(str), "{results: [%M]}", &scan_array);

return 0;
}

输出:

Parsing {"success":true,"errors":[],"results":[{"productConditionId":3442759,"price":169.54,"lowestRange":155.00,"highestRange":229.95}]} 
Parsing array: [{"productConditionId":3442759,"price":169.54,"lowestRange":155.00,"highestRange":229.95}]
Index 0, token {"productConditionId":3442759,"price":169.54,"lowestRange":155.00,"highestRange":229.95}
Price 169.54 : price casted 169

关于c - 使用C语言解析JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54875383/

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