jsonjqpretty-printjsonlint

how to prettyprint a single-quoted JSON file using jq


{ 'abc': { 'name': 'John', 'address': 'USA' }, 'xyz': { 'name': 'Robert', 'address': 'Canada' } }


Solution

    1. The sample is not valid JSON.

    2. jq can be used to pretty-print valid JSON, though there are some important caveats, mainly about numbers. For example:

      $ jq . <<< '{ "abc": { "name": "John", "address": "USA" }, "xyz": { "name": "Robert", "address": "Canada" } }'  
      {
        "abc": {
          "name": "John",
          "address": "USA"
        },
        "xyz": {
          "name": "Robert",
          "address": "Canada"
        }
      }
      
    3. See the jq FAQ for information about converting not-quite-valid JSON to JSON -- search for not-quite-valid.

    4. At least one of the tools mentioned in the above-referenced section in the jq FAQ (jsonlint) will not only convert single-quoted quasi-JSON to JSON, but also pretty-print it.

    5. In the example you gave, you could use sed or even tr in conjunction with jq:

      echo "{ 'abc': { 'name': 'John', 'address': 'USA' }, 'xyz': { 'name': 'Robert', 'address': 'Canada' } }" |
        tr "'" '"' | jq .
      {
        "abc": {
          "name": "John",
          "address": "USA"
        },
        "xyz": {
          "name": "Robert",
          "address": "Canada"
        }
      }