5

I have a json file. If I run clang-format on it, it formats it as though it's code (ugly).

{
  "name" : "My great app",
           "description" : "It's really cool.",
                           "version" : "0.0.1"
}

If I put 'foo = ' at the start of the file, it's great, but it's not json anymore.

foo = {
  "name" : "My great app",
  "description" : "It's really cool.",
  "version" : "0.0.1"
}

How can I get clang-format to format the bare object in the json file as in the second example?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Chris Connett
  • 147
  • 1
  • 7

4 Answers4

3

I've been working on getting this accepted, https://reviews.llvm.org/D93528, this does what you suggest by adding a hidden "x = " at the front of the file, then remove that after formatting using the replacement mechanism.

Until this gets landed I think you could do something similar perhaps with clang-apply-replacements

MyDeveloperDay
  • 2,485
  • 1
  • 17
  • 20
2

Personally I'd do it using python, using the json's package pretty printer:

cat mydata.json | python -mjson.tool

and if you don't like the defaults:

cat mydata.json | python -c 'import json, sys; print(json.dumps(json.load(sys.stdin), indent=4, sort_keys=True))'

Otherwise, I don't have clang-format installed, and for the sake of pretty printing, I'd rather use an existing tool.

N.B.: You can also do it within vim and use the == normal command on the full file selection ☺

zmo
  • 24,463
  • 4
  • 54
  • 90
2

Another program that I like to use is jq. It's pretty easy to use, and the documentation is great. For example, for simple reformatting you can do this:

jq . test.json
PythonJin
  • 4,034
  • 4
  • 32
  • 40
0

If you have json_pp on your system you can also do:

cat test.json | json_pp
PythonJin
  • 4,034
  • 4
  • 32
  • 40