我有一个选择并提取 JSON 行的函数。该 JSON 行将在另一个函数中计算,该函数应该提取它的值。
"key" : "value",
我希望在不使用任何用于操作 JSON 的库的情况下提取值。
到目前为止我的代码看起来像这样:
char* extractValueInLine(char* line) {
if(!verifyLine(line)) // Checks wether line contains 4 quotes or not
return "";
int len = strlen( line );
char* res = NULL;
unsigned quoteCpt = 0;
for (unsigned i = 0; i < len; i++){
if (line[i] == '\"')
quoteCpt++;
if (quoteCpt == 3) // If 3 quotes has been skipped
{
res = malloc((char) sizeof(res) + sizeof(char)); // Adding memory for one char
if (NULL == res)
fprintf(stderr, "Not enough memory.\n");
else
{
char toAppend[2];
toAppend[1] = '\0';
toAppend[0] = line[i];
strcat(res, toAppend); // Append current char
}
}
return res;
}
这非常难看,而且效率很低,因为输出是空白而不是值。
尽管如此,我已经尝试了越来越多的方法来做到这一点,使用字符串库函数以及 sscanf、strtok 等,但它要么不起作用,要么很容易损坏。
即使添加或缺少空格也能工作的代码将是完美的。
如果有人可以给我建议或告诉我我在这里缺少什么。
最佳答案
使用strchr()
查找引号的位置。然后,利用该信息提取值。
类似的东西
char *q1 = strchr(line, '\"'); /* needs error checking */
char *q2 = strchr(q1 + 1, '\"');
char *q3 = strchr(q2 + 1, '\"');
char *q4 = strchr(q3 + 1, '\"');
/* allocate (q4 - q3) bytes for res */
sprintf(res, "%.*s", (int)(q4 - q3 - 1), q3 + 1);
关于c - 在C中从JSON中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43753963/