+ 3

C - json & struct

I've a json I'm reading each lines, but I don't how to save them on a struct to have an array. Json : [ { "name": "knife", " damages": 4 } ] C struct : typedef struct Weapons { int damages; char name[50]; } Weapon; I'm reading json without a lib, I'm trying to do it myself. So for now I only have FILE* file = NULL; char str[60] = ""; file = fopen("json/weapons.json", "r"); if(file != NULL) { while(fgets(str, 60, file) != NULL) { puts(str); } } If you know how to finish this project :/

23rd Jan 2019, 7:50 PM
NoxFly
NoxFly - avatar
8 Answers
+ 3
"Comma Separated Values" Basically a format to store databases as easy as cell1;cell2;cell3 stuff;thing;idek NoxFly ドăƒȘケン
23rd Jan 2019, 11:58 PM
Dapper Mink
Dapper Mink - avatar
+ 3
Its cool but if I can I'll try to keep json
24th Jan 2019, 12:01 AM
NoxFly
NoxFly - avatar
+ 2
json is a fairly easy format but if you want to implement a full-blown json parser that will still be a few hundred lines of code. You might be better off saving your data in a format like CSV!
23rd Jan 2019, 11:38 PM
Schindlabua
Schindlabua - avatar
+ 2
Whats CSV ? Schindlabua
23rd Jan 2019, 11:56 PM
NoxFly
NoxFly - avatar
+ 1
What's your problem? How to parse the data or how to implement a JSON structure in C?
23rd Jan 2019, 8:39 PM
Dapper Mink
Dapper Mink - avatar
0
You can use a structure array to save them can you include the syntex of the file also then i can give you the exact code to save your needing value to your structure
23rd Jan 2019, 8:26 PM
Sahil Bhakat
Sahil Bhakat - avatar
0
I guess this will help typedef struct { int damages; char str [60]= NULL; }weapons; int main() { int x,i=0; weapons w [size of the array ]; //in the while loop { sscanf(str,"%s",x); w[i].damages=x; fgets(str,60,file); strcpy(w[i],str); i++; } } I am sure you can do the error handling
23rd Jan 2019, 9:10 PM
Sahil Bhakat
Sahil Bhakat - avatar
0
NoxFly ドăƒȘケン The first step then would be to read the input string character by character, and split it into "tokens", which are the smallest units of information. For example the json string `{"a" : ["thing":40, "x":{}]}` would probably be split into the tokens: {, "a", :, [, "thing", :, 40, "x", :, {, }, ], } And once you have a list of tokens, you can try to make sense of them. The hard part is that in json, objects may contain other objects and you can nest them as deep as you want. Though, just writing a tokenizer is already tricky! It might be too much work for what you are trying to do, but if you are up for a challenge then I encourage trying it of course :) I can help if you're stuck. (Makes you appreciate the amount of work that goes into javascript's JSON.parse(x))
24th Jan 2019, 12:22 AM
Schindlabua
Schindlabua - avatar