使用groovy中的每个对解析的json对象进行条件迭代

时间:2017-04-05 03:41:41

标签: groovy

我正在尝试根据.json中的数据创建XML。因此,我的.json文件类似于:

{
  "fruit1":
    {
      "name": "apple",
      "quantity": "three",
      "taste": "good",
      "color": { "walmart": "{{red}}","tj": "{{green}}" }
    },
  "fruit2":
    {
      "name": "banana",
      "quantity": "five",
      "taste": "okay",
      "color": { "walmart": "{{gmo}}","tj": "{{organic}}" }
    }
}

我可以使用以上代码从上面的json

创建XML
import groovy.xml.*
import groovy.json.JsonSlurper

def GenerateXML() {
  def jsonSlurper = new JsonSlurper();
  def fileReader = new BufferedReader(
                  new FileReader("/home/workspace/sample.json"))
  def parsedData = jsonSlurper.parse(fileReader)
  def writer = new FileWriter("sample.XML")
  def builder = new StreamingMarkupBuilder()
  builder.encoding = 'UTF-8'
  writer << builder.bind {
    mkp.xmlDeclaration()
    "friuts"(version:'$number', application: "FunApp"){
      delegate.deployables {
     parsedData.each { index, obj ->
       "fruit"(name:obj.name, quantity:obj.quantity) {
            delegate.taste(obj.taste)
            delegate.color {
            obj.color.each { name, value ->
              it.entry(key:name, value)
              }
            }
          }
        }
      }
    }
  }

}

我想扩展此代码,以便查找特定键。如果它们存在,那么也会为那些maps执行循环,并因此扩展生成的文件。

所以,如果我有这样的JSON:

{"fruit1":
  {
    "name": "apple",
    "quantity": "three",
    "taste": "good",
    "color": { "walmart": "{{red}}","tj": "{{green}}" }
  },
  "fruit2":
  {
    "name": "banana",
    "quantity": "five",
    "taste": "okay",
    "color": { "walmart": "{{gmo}}","tj": "{{organic}}" }
  },
  "chip1":
  {
    "name": "lays",
    "quantity": "one",
    "type": "baked"
  },
  "chip2":
  {
    "name": "somename",
    "quantity": "one",
    "type": "fried"
  }
}

我想添加一个IF,以便检查是否有'chip*'之类的任何键。如果是,则执行另一次迭代。如果不是只跳过那部分逻辑,而不是抛出任何err。像这样

import groovy.xml.*
import groovy.json.JsonSlurper

def GenerateXML() {
  def jsonSlurper = new JsonSlurper();
  def fileReader = new BufferedReader(
                  new FileReader("/home/okram/workspace/objectsRepo/sample.json"))
  def parsedData = jsonSlurper.parse(fileReader)
  def writer = new FileWriter("sample.XML")
  def builder = new StreamingMarkupBuilder()
  builder.encoding = 'UTF-8'
  writer << builder.bind {
    mkp.xmlDeclaration()
    "fruits"(version:'$number', application: "FunApp"){
     deployables {
     parsedData.each { index, obj ->
       "fruit"(name:obj.name, quantity:obj.quantity) {
            taste(obj.taste)
            color {
            obj.color.each { name, value ->
              it.entry(key:name, value)
              }
            }
          }
        }
      }
    }
    if (parsedData.containsKey('chip*')){
      //perform the iteration of the chip* maps
      //to access the corresponding values
      //below code fails, but that is the intent     
      parsedData.<onlyTheOnesPassing>.each { index1, obj1 -> 
         "Chips"(name:obj1.name, quantity:obj1.quantity) {
           type(obj1.type)
         }

      } 

      }

    }
  }

1 个答案:

答案 0 :(得分:1)

我发现同样的困难,但是在 Javascript 语言中,如果逻辑帮助你,我在这里做的是:

有两种方式:

您可以在&#34; get&#34;上使用Lodash库。在这里:Lodash get或另一个&#34;有&#34;:Lodash has

使用它们,您可以放置​​对象和路径,并检查是否存在任何错误。

示例:

&#13;
&#13;
_.has(object, 'chip1.name');
// => false

_.has(object, 'fruit1');
// => true
&#13;
&#13;
&#13;

或者你可以把方法的代码放在这里:

&#13;
&#13;
// Recursively checks the nested properties of an object and returns the
	// object property in case it exists.
	static get(obj, key) {
		return key.split(".").reduce(function (o, x) {
			return (typeof o == "undefined" || o === null) ? o : o[x];
		}, obj);
	}

	// Recursively checks the nested properties of an object and returns
	//true in case it exists.
	static has(obj, key) {
		return key.split(".").every(function (x) {
			if (typeof obj != "object" || obj === null || !x in obj)
			return false;
			obj = obj[x];
			return true;
		});
	}
&#13;
&#13;
&#13;

我希望它有所帮助! :)