0

I've got a program that outputs data in json format. I'm wanting to read from that program and parse the json data, then add my own variables to the json object. I'm lost on how to parse the data once i've done the file open and read. any suggestions on how to parse through it, maybe assign a name to the newly created object?

I'm on linux, writing in C.

#include <stdio.h>
#include <json/json.h>





int main(int argc, char ** argv){
printf("Getting Location Data from pipe: \n");

FILE *in;
extern FILE *popen();
char gps_stream[4096];

if(!(in = popen("gpspipe -w", "r"))){
    printf("Cant do it!\n");
}

while(fgets(gps_stream, sizeof(gps_stream), in)!=NULL){


json_object * jobj = json_tokener_parse(gps_stream);


}
pclose(in);


}
3
  • Can you specify which JSON parsing software/library you're using? Commented Feb 9, 2014 at 23:14
  • In general you should obtain a JSON parser package. If you go to json.org there are a bunch listed that you can choose from. (But note that dealing with JSON in C vs C++ is tricky, since basic C lacks the data structures to deal with "maps" and "lists", while C++, Java, Objective-C, et al have such structures in their standard libraries.) Commented Feb 9, 2014 at 23:17
  • Here's what I've been using: rpm.pbone.net/index.php3/stat/4/idpl/19570900/dir/redhat_el_6/… Commented Feb 10, 2014 at 16:46

1 Answer 1

1

If you are this lost, please don't write your own json parser. Use one of the many libraries out there, like libyajl to do it for you.

Sign up to request clarification or add additional context in comments.

4 Comments

Actually, in C++ or Objective-C or Qt you can write a basic parser (that won't necessarily handle the oddball cases) in about 500 lines of code. But you'd have to write at least another 500, maybe 1500, in vanilla C in order to invent the supporting classes. It's an interesting exercise, but not real productive when there are other options.
Well that may be true, but this question is about C (not C++ or objective C which are different languages) - see tags. Qt is not a language, but a framework for C++, so has nothing much to do with the question either. Having seen people attempt to write JSON parsers in C who are a little lost in C to start with, I can tell you the best thing is to use a pre-existing library.
Right. If you know the language it's not a big deal, but if not then you'll get into trouble from several angles.
Consider also using jansson which is another C library for JSON....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.