0

If I have this JSON

{
 a: {
  b: {
   c: {
    id: "some-key",
    d: {
     e: {
      <thousands and thousands of lines>
     }
    },
    "this": "is the field I want"
   }
  }
 }
}

How would I just return the properties of c?

Reason for doing this, I need to identify an object with eg. "id": "some-key" and return one of its other properties. In my example, d and e could be many Mbs. I originally did this using JsonSlurper but the file is so big I ran out of memory. I've already set -Xmx2048m to no avail. Before I consider downloading more memory I'm assuming there must be some way of parsing the JSON without actually storing it? I'd rather use something that exists instead of writing my own parser.

Rob H
  • 47
  • 5
  • 1
    what does it mean: `e: { }` ? is there a large object ? or array? or just large text data? – daggett Jul 06 '21 at 16:17
  • Have you looked at what Jackson has to offer? E.g. https://stackoverflow.com/questions/24835431/use-jackson-to-stream-parse-an-array-of-json-objects - AFAIK there is no "shortcut" to lazy loading with groovy-json. – cfrick Jul 06 '21 at 17:29

1 Answers1

1

i've seen this one:

@Grab(group='acme.groovy', module='acmejson', version='20.04.02')
import groovyx.acme.json.AcmeJsonParser

//parse but ignore all values inside `c.d`
def json = new AcmeJsonParser().withFilter{
    onValue('$..c.d..'){value,path->
        return null
    }
    build()
}.parse(new File("/11/tmp/1.json"))
println json

or

//parse but not build in-memory object
def id,_this
new AcmeJsonParser().withFilter{
    onValue('$..c.id'){value,path->
        id = value
    }
    onValue('$..c.this'){value,path->
        _this = value
    }
}.parse(new File("/11/tmp/1.json"))
daggett
  • 26,404
  • 3
  • 40
  • 56
  • Looks like the perfect solution so will accept as answer. Unfortunately, can't test until allowed external access. – Rob H Jul 07 '21 at 08:42