0

I have started by programming with Golang, and things looked easy.Then I stumbled on JSON parser of C (JSMN) so that I can try CGO.

Here's the code lines (11 and 46) from this example:

static const char *JSON_STRING =
    "{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n  "
    "\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";

printf("- User: %.*s\n", t[i+1].end-t[i+1].start, JSON_STRING + t[i+1].start);

This gives me result:

"- User: johndoe"

I am new to C. I want to get the value "johndoe" into a variable. I tried below code its giving me NULL:

int c = 0;
char sub[1000];
while (c < (t[i+1].end-t[i+1].start) ) {
    sub[c] = JSON_STRING[t[i+1].start+c-1];
    c++;
}
sub[c] = '\0';

Output:

"-User: null "

How can I do that? Thanks!

Azeem
  • 11,148
  • 4
  • 27
  • 40
tony
  • 33
  • 3
  • Have you tried printing the assignment variable (`JSON_STRING[t[i+1].start+c-1]`) for few values of `c` and the condition variable (`t[i+1].end-t[i+1].start`) separately to check what it holds? PLUS what do you mean by - "giving me NULL"? – Gaurav Sep 22 '18 at 19:55
  • `JSON_STRING` looks like a constant and you are trying to access `JSON_STRING[t[i+1].start+c-1]´ – amine.ahd Sep 22 '18 at 20:39
  • Have a look at `sprintf` and `snprintf` in [printf(3) - Linux manual page](http://man7.org/linux/man-pages/man3/printf.3.html) – David C. Rankin Sep 23 '18 at 02:44
  • Added details about NULL and JSON-STRING above – tony Sep 23 '18 at 04:42
  • Which code do you use to print `sub`? – alk Sep 23 '18 at 10:09
  • "*`... = JSON_STRING[t[i+1].start+c-1];`*": Why the `-1`? – alk Sep 23 '18 at 10:10

1 Answers1

0

You can use strncpy() to copy the required string in a separate variable as you already know the length and the starting point of the string i.e.:

t[i+1].end - t[i+1].start     // length of the string to copy
JSON_STRING + t[i+1].start    // starting point from where to start copying

For example:

const char*  strStart  = JSON_STRING + t[i+1].start;
const size_t strLength = t[i+1].end - t[i+1].start;

const size_t length = 8;      // required to store "johndoe"
char strCopy[ length ] = { 0 };

strncpy( strCopy, strStart, strLength );
// You might need to null terminate your string
// depending upon your specific use case.

JSMN parser stores the start and end positions of tokens. The user of the library is required to make copies as and when required using these positions.

%.*s format specifier in printf() takes field width (string length to be printed) preceding the actual C-style string as arguments. For more details, see this.

Azeem
  • 11,148
  • 4
  • 27
  • 40