首页 > 解决方案 > 如何读取 C 中特定关键字的 json 数据包?

问题描述

这是我的 json 数据包,我想阅读“14.469121”:

{"jsonrpc": "2.0", "method": "notifySpeed", "params": {"speed": "14.469121"}}

我尝试了一些在线解决方案并实现了一些逻辑。

ptr = strtok(parse_recData,", ");

     while(ptr != NULL)
     {
         countTillMethod--;
         if(countTillMethod == 0)
         {
             if(strcmp(ptr,"\"notifySpeed\"")==0)
             {
              if(!(strcmp(ptr,"\"Speed\"" )))

                Speed = strtok(NULL,", ");

                 SpeedValue = atoi (Speed);

                 if (SpeedValue > PERMISSIBLE_LIMIT)
                            touchControl (DISABLE);
                 else
                            touchControl (ENABLE);
            }
         }
     }

我想读取速度数据。

标签: cjson

解决方案


谢谢大家的帮助,终于我成功实施了。

         else if(strcmp(ptr,"\"notifySpeed\"")==0)
         {
             syslog(LOG_INFO,"Received Speed\n");
             ptr1 = strstr(parse_recData_backup, "\"params\"");
             ptr1 += strlen("params");
             ptr1 = strstr(parse_recData_backup, "\"speed\": ");
             ptr1 += strlen("\"speed\": ") + 1;

             /* get the exect value */
             for(i=0; ptr[i]!='\0'; ++i)
             {
             while (!((ptr1[i]>='0'&&ptr1[i]<='9') || (ptr1[i] == '.') || (ptr1[i] == '\0')))
             {
                    for(j=i;ptr1[j]!='\0';++j)
                    {
                    ptr1[j]=ptr1[j+1];
                    }
                    ptr1[j]='\0';
             }
             }
             syslog(LOG_INFO," %s \r\n", ptr1);

             /* Converts the string to integer */
             Speed = atoi(ptr1);
             syslog(LOG_INFO," speed is %d \r\n", Speed);

             /* Compare the speed with permissiable limit */
             if (Speed > PERMISSIBLE_LIMIT)
                        touchControl (DISABLE);
             else
                        touchControl (ENABLE);

         }

推荐阅读