Brett
Brett

Reputation: 931

sort json document using jq

I have a json document that is a (SSAS Tabular model .bim file)

Its full structure is attached example json but it is a nested object structure as per below. Every object has a name property that I would like to use to sort on

{
"name": "SemanticModel",
"compatibilityLevel": 1200,
"model": {
"culture": "en-US",
"dataSources": [
  {
    "name": "BlahDW",
    "connectionString": "Provider=SQLOLEDB;Data Source=sql.blah.com;Persist Security Info=false;Integrated Security=SSPI;Initial Catalog=Blah",
    "impersonationMode": "impersonateAccount",
    "account": "blah\\blah",
    "annotations": [
      {
        "name": "ConnectionEditUISource",
        "value": "SqlServer"
      }
    ]
  }
],
"tables": [
  {
    "name": "Employees",
    "isHidden": true,
    "columns": [
      {
        "name": "Employee Key",
        "dataType": "int64",
        "isHidden": true,
        "isUnique": true,
        "isNullable": false,
        "sourceColumn": "Employee Key"
      },
      {
        "name": "Employee Code",
        "dataType": "string",
        "isHidden": true,
        "sourceColumn": "Employee Code"
      },
      {
        "name": "Employee Name",
        "dataType": "string",
        "isHidden": true,
        "sourceColumn": "Employee Name"
      },
      {
        "name": "Home Village Code",
        "dataType": "string",
        "isHidden": true,
        "sourceColumn": "Home Village Code"
      }
    ],
....

I have tried the walk/1 method as mentioned here How can I completely sort arbitrary JSON using jq? but it doesn't work as it is not trying to sort the objects in the collections I don't think.

I have found that this works ".model.tables|=sort_by(.name)" to just sort one collection (thanks to How to sort a json file by keys and values of those keys in jq) but I cannot work out how to combine this with the walk so I don't need to explicitly recreate the same json structure

I am at my limit of my jq knowledge here so wondered if someone could put me in the right direction

Upvotes: 0

Views: 3302

Answers (1)

zeppelin
zeppelin

Reputation: 9365

You can sort all the arrays by "name", while keeping everything else intact, like this:

walk(if type == "array" then sort_by(.name) else . end)

Upvotes: 4

Related Questions