2012-05-22 2 views
1

숫자 필드에 제공된 문자열 표현에 액세스 할 수있는 C 기반 JSON 구문 분석기를 아는 사람이 있습니까? 무슨 뜻으로 예를 들어 :숫자를 파싱하는 것에 대해 게으른 JSON 파서?

json_t * dist = json_object_get(coord, "accuracy"); 
snprintf(dataOut->distance, MAX_COORD_LEN, "%f", json_number_value(dist)); 

이것은 단위 테스트를 작성하는 것은 어리 석고 어렵습니다. 나는 단순히 json_string_value(dist)을 호출하고 그 번호에 들어온 문자열을 정확히 얻는 것을 선호한다. 그 문자열을 숫자로 바꾸는 것을 고심하지는 않을 것입니다. 그런 식으로 "54.6045"를 포함하는 테스트 문자열에 해당 필드를 입력하면 "54.6045"가 반환되고 패딩되거나 반올림 된 값은 반환되지 않습니다. 그리고 결코 그 번호를 파싱하지 않아도됩니다. 그것을 하나로 사용하십시오.

제가 말할 수있는 한, 그런 것은 없습니다 ... 나는 아주 바보 같습니다. 위의 예제는 Jansson에서 왔으며 문자열 값 함수를 사용하면 null을 반환합니다.

나는 이것 때문에 자기 자신을 쓰지 않아도되는 것을 정말로 좋아할 것이다.

당신이 이미 알고하지 않은 경우
+2

, 왜 당신은 문자열을하지 않는다? 입력을 제어하지 않기 때문입니까? –

답변

2

http://www.json.org/ 나는 자원 제약에 대한 jsmn을 사용하고

C.

에 그들 중 12 등, 다양한 언어로 작성된 JSON 라이브러리의 목록을 유지 , 임베디드 플랫폼. 그것이하는 일은 JSON 문자열을 토큰 화하기 만하면되므로 라이브러리에서 필요한 것을 얻을 수 있지만 유용하게 사용할 수 있도록 조금 더 로직을 만들어야합니다.

마찬가지로 JSON_checker를 사용자가 원하는대로 조정할 수 있습니다.

원하는 것을 찾지 못하면 자신을 분석하는 것이 어렵지 않습니다.

+0

나는 그것을 조사 할 것이다. 문서 링크가 404를 가리 키기 때문에 저를 깜짝 놀라게했습니다. –

-2

Jansson은 훌륭한 라이브러리이며 단위 테스트를 기반으로 다른 라이브러리를 선택하는 것은 수치 스럽습니다. 왜 숫자 값을 파싱하는 것에 반대하는지 모르겠습니다. 설명 할 수 있습니까?

코드 스 니펫에 관한 한, 구조에서 숫자 값을 검색하는 데 관련된 상용구에 약간의 짜증이 날 수 있습니다. json_pack/json_unpack 함수를 좋아하는 것을 배우는 것이 좋습니다. 다음과 같이 사전의 정수 요소를 검색 할 수 있습니다

double d; 
json_unpack(coord, "{s:f}", "accuracy", &d); 

이 호출을 사용하여 부동 소수점 값을 나타내는 (json_t *) 개체로 작업 할 필요가 없습니다. 물론 json_unpack() 호출의 리턴 코드에서 오류 조건을 확인해야합니다.

당신은 여기에 짧은 버전입니다, 요구하는 것을 정확하게 보여줍니다 README 파일의 예입니다 https://github.com/cesanta/frozen

사용할 수 있습니다

+0

누군가가 JSON 문자열에서 숫자의 문자열 표현을 가져 오는 것과 다른 방법을 두 번 읽음으로써 이중으로 구문 분석하지 않는 것에 대한 질문에 답하는 이유는 무엇입니까 ?? –

0

:

static const char *str = " { foo: { bar: [ 80, 443 ], baz: 1.2e-21 } } "; 
struct json_token tokens[50]; 
int size = sizeof(tokens)/sizeof(tokens[0]); 
const struct json_token *tok = NULL; 

parse_json(str, strlen(str), tokens, size); 
tok = find_json_token(tokens, "foo.bar[1]"); 
printf("My number is: [%.*s]\n", tok->len, tok->ptr) 
0

작은-JSON이 허용하는 C 파서는 가장 간단한 방법으로 숫자 필드에 들어온 문자열 표현에 액세스 할 수 있습니다. JSON 속성을 요청하면 값으로 null-terminated에 대한 포인터를 반환합니다. 당신은 그냥 문자열로 사용하는 경우 https://github.com/rafagafe/tiny-json

#include <stdio.h> 
#include "tiny-json.h" 

int main(int argc, char** argv) { 

    char str[] = "{\"accuracy\":654,\"real\":2.54e-3}"; 

    // In the example only 3 is needed. For root and two fields. 
    json_t mem[ 3 ]; 

    json_t const* root = json_create(str, mem, sizeof mem/sizeof *mem); 
    if (!root) { 
     fputs("Cannot create a JSON.\n", stderr); 
     return 1; 
    } 

    { // You can get the primitive values as text format: 

     char const* accuracy = json_getPropertyValue(root, "accuracy"); 
     if (!accuracy) { 
      fputs("The filed 'accuracy' is not found.\n", stderr); 
      return 1; 
     } 
     printf("The accuracy value: %s\n", accuracy); 

     char const* real = json_getPropertyValue(root, "real"); 
     if (!real) { 
      fputs("The filed 'real' is not found.\n", stderr); 
      return 1; 
     } 
     printf("The real value: %s\n", real); 

    } 

    { // You can check the type of a field and get its value in binary format: 

     json_t const* accuracy = json_getProperty(root, "accuracy"); 
     if (!accuracy) { 
      fputs("The filed 'accuracy' is not found.\n", stderr); 
      return 1; 
     } 
     if(json_getType(accuracy) != JSON_INTEGER) { 
      fputs("The filed 'accuracy' is not an integer.\n", stderr); 
      return 1; 
     } 
     // Get the value in binary format: 
     long long accuracyVal = json_getInteger(accuracy); 
     printf("The accuracy value: %lld\n", accuracyVal); 
     // Get the value in text format: 
     char const* accuracyTxt = json_getValue(accuracy); 
     printf("The accuracy value: %s\n", accuracyTxt); 

     json_t const* real = json_getProperty(root, "real"); 
     if (!accuracy) { 
      fputs("The filed 'real' is not found.\n", stderr); 
      return 1; 
     } 
     if(json_getType(real) != JSON_REAL) { 
      fputs("The filed 'real' is not a real.\n", stderr); 
      return 1; 
     } 
     // Get the value in binary format: 
     double realVal = json_getReal(real); 
     printf("The real value: %f\n", realVal); 
     // Get the value in text format: 
     char const* realTxt = json_getValue(real); 
     printf("The real value: %s\n", realTxt); 

    } 

    return 0; 
}