c - 在C中从JSON中提取字符串

标签 c json string memory

我有一个选择并提取 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/

相关文章:

java - 如何对帖子主体对象使用@SerializedName注释

javascript - D3.json 设置缓存为 false

java - Spring MVC 中的 Jackson Field 过滤器

string - 如何在 Notepad++ 中使用退格转义序列?

asp.net - 在 ASP .NET 上的 DataList 项内的 LinkBut​​ton 中添加 Javascript 字符串值

c - 如果此代码中 consed 对象的 car 和 cdr 是整数,如何打印它们?

c - 是否可以在严格的程序程序中避免使用全局变量?

c - 使用结构变量时出现链接器错误

c - 检查 POSIX THREAD 堆栈上内存泄漏的最佳方法?

c++ - 另外重载的代码没有效果