Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding JSON as a string in C++ code using preprocessor

I saw a mix of C++ and JSON code in the Chromium project.

For example in this file: config/software_rendering_list_json.cc

Is the magic with this macro?

#define LONG_STRING_CONST(...) #__VA_ARGS__

How does it "stringify" arbitrary JSON content?

like image 675
rustyx Avatar asked Aug 18 '15 20:08

rustyx


Video Answer


1 Answers

Cameron's answer is absolutely correct.

However, since C++11, there is a compiler supported method for creating raw string literals.

char const *string = R"someToken({
  "name": "software rendering list",
  "version": "10.9",
  "entries": [
    {
      "id": 1,
      "description": "ATI Radeon X1900 is not compatible with WebGL on the Mac",
      "webkit_bugs": [47028],
      "os": {
        "type": "macosx"
      },
      "vendor_id": "0x1002",
      "device_id": ["0x7249"],
      "features": [
        "webgl",
        "flash_3d",
        "flash_stage3d"
      ]
    },
    {
      "id": 3,
      "description": "GL driver is software rendered. GPU acceleration is disabled",
      "cr_bugs": [59302, 315217],
      "os": {
        "type": "linux"
      },
      "gl_renderer": "(?i).*software.*",
      "features": [
        "all"
      ]
    }
  ]
})someToken";

Note, however, that there are several subtle differences.

Most obviously, the macro will get rid of C/C++ comments and the macro will coalesce all whitespace into a single space.

Further details about string literals can be found in lots of places. I like this one.

like image 102
Jody Hagins Avatar answered Oct 01 '22 14:10

Jody Hagins