tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.39k stars 857 forks source link

help with a query to get all paths in a nested json #337

Closed shabbskagalwala closed 1 year ago

shabbskagalwala commented 1 year ago

First of all thank you for this awesome project! I am trying to implement this in one of our libraries to get values from nested objects. The problem is our json structure is not known, but the key names will always be the same. For example

{
  "us-west-2": {
    "dev": {
      "service1": {
        "cost": "float",
        "type": "string",
        "count": "int"
      },
      "service2": {
        "cost": "float",
        "type": "string",
        "count": "int"
      }
    },
    "prd": {
      "service1": {
        "cost": "float",
        "type": "string",
        "count": "int"
      }
    }
  },
  "us-east-1": {
    "dev": {
      "service1": {
        "cost": "float",
        "type": "string",
        "count": "int"
      },
      "service2": {
        "cost": "float",
        "type": "string",
        "count": "int"
      }
    },
    "prd": {
      "service1": {
        "cost": "float",
        "type": "string",
        "count": "int"
      }
    }
  }
}

Is there a way for me to get the values for the count and cost keys in each top level key us-west-2 and us-east-1. The problem is the json structure is dynamic, in some cases we'll have only us-west-2 in other cases there'll be no us-west-2 and many other values and similar for the nested keys as well. The only thing common will be

        "cost": "float",
        "type": "string",
        "count": "int"

Thank you!

volans- commented 1 year ago

@shabbskagalwala In recent gjson versions (I think since v1.16.0) there is the new @dig modifier (see SYNTAX.md#modifiers ) that combined with multipaths could be used for example like this:

{"count":@dig:count,"cost":@dig:cost}

to get (I've pretty-fied the output for easier readability):

{
  "count": ["int", "int", "int", "int", "int", "int"],
  "cost": ["float", "float", "float", "float", "float", "float"]
}

I'm not sure this is what you're looking for. If not, could you provide an example of output you are looking for?

shabbskagalwala commented 1 year ago

Thank you so much - i should have read the docs! Appreciate your help :) This can be closed.