Omkar Amberkar
Omkar Amberkar

Reputation: 2482

How to parse .json file with a gradle task and get the json data from it?

Is there a way where in I can parse a xyz.json file with help of a gradle task and get all the individual json data inside it? for eg. I want to parse this data which is stored in a xyz.json file in my assets folder and get all the values inside it, eg. get the value of "type".

{
  "type":"xyz",
  "properties": {
    "foo": {
      "type": "pqr"
    },
    "bar": {
      "type": "abc"
    },
    "baz": {
      "type": "lmo"
    }
  }
}

Upvotes: 10

Views: 15036

Answers (3)

Steephen
Steephen

Reputation: 15824

If you want to parse a json file in build.gradle.kts do as follows:

import groovy.json.JsonSlurper
val VersionsMap: Map<String, String> by extra {
    JsonSlurper().parse(file("xyz.json")) as Map<String, String>
}
val value = VersionMap.get("key")

Upvotes: 2

jitinsharma
jitinsharma

Reputation: 1476

You can create a gradle task like this

gradle myTask{
 doLast{
  def inputFile = new File("xyz.json")
  def json = new JsonSlurper().parseText(inputFile.text)
  def labels = json.properties.foo.type //This will return "pqr"
 }
}

Upvotes: 25

David M. Karr
David M. Karr

Reputation: 15235

Gradle build scripts are just Groovy scripts. Read the Gradle User Guide to learn how to write custom tasks, and use the JsonSlurper class to parse your json file.

Upvotes: -3

Related Questions