tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
13.88k stars 841 forks source link

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

Closed shabbskagalwala closed 8 months ago

shabbskagalwala commented 8 months 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 8 months 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 8 months ago

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