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
  • 41,615
  • 22
  • 193
  • 161

4 Answers4

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
  • 3,714
  • 4
  • 34
  • 40
2

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,323
  • 1
  • 15
  • 18
1

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
  • 23,731
  • 4
  • 53
  • 86
0

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

cat test.json | json_pp
PythonJin
  • 3,714
  • 4
  • 34
  • 40