如何更改jsonslurped lazymap条目的值(和类型)

时间:2016-03-21 14:33:42

标签: json groovy eval jsonslurper

我有以下JSON:

{"name":"Guillaume","age":33,"address":"main st","pets":[{"type":"dog", "color":"brown"},{"type":"dog", "color":"brown"}]}}

我使用JsonSlurper来解析它。我需要能够根据各种标准修改JSON的内容。我想要修改的键是外部定义的。

我可以轻松更改字符串值,如下所示。下面的结果是lazyMap中的地址字段从" main st"到"第二个"。

import groovy.json.JsonSlurper
def slurper = new JsonSlurper()  
def result = slurper.parseText('{"person": {"name":"Guillaume","age":33,"address":"main st","pets":[{"type":"dog", "color":"brown"},{"type":"dog", "color":"brown"}]}}')
String address = "result.person.address"  // Note: this is externalized
String newAddressValue = "second st"
Eval.me('result', result, "$address = '$newAddressValue'")
println result.person.address

我似乎无法解决的问题是,是否要将地址值从字符串更改为地图。

import groovy.json.JsonSlurper
def slurper = new JsonSlurper()  
def result = slurper.parseText('{"person": {"name":"Guillaume","age":33,"address":"main st","pets":[{"type":"dog", "color":"brown"},{"type":"dog", "color":"brown"}]}}')

Map newAddressMap = slurper.parseText(/{"street":"Third Street", "city":"New York", "state":"New York"}/)

Eval.me('result', result, "$address = $newAddressMap")
println result.person.address.getClass()
println result.person.address

上面的$ newAddressMap被解释为字符串,导致以下错误:

  

启动失败:Script1.groovy:1:当前范围已包含   一个名为York @ line 1,第51列的变量.s = [city:New   约克,州:纽约,街区

但是,下面的工作(将地址键值从String更改为LazyMap),但需要我的密钥是已知的/硬编码的:

result.person.address = newAddressMap
println result.person.address.getClass()
println result.person.address

下面没有错误,但$ newAddressMap是一个字符串和lazyMap键"地址"仍然是一个字符串。

Eval.me('result', result, "$address = '$newAddressMap'")
println result.person.address.getClass()
println result.person.address

如何在运行时定义地址键值的同时将地址键值从String更改为Map?

1 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

import groovy.json.*

def slurper = new JsonSlurper()
// Given your document
def document = slurper.parseText('{"person": {"name":"Guillaume","age":33,"address":"main st","pets":[{"type":"dog", "color":"brown"},{"type":"dog", "color":"brown"}]}}')
// And your replacement
def newAddressMap = slurper.parseText('{"street":"Third Street", "city":"New York", "state":"New York"}')

// And the location of the attribute you want to replace
def addressPath = 'person.address'

// Split the path, and replace the property with the new map (this mutates document)
addressPath.split('\\.').with {
    def parent = it[0..-2].inject(document) { d, k -> d."$k" }
    parent[it[-1]] = newAddressMap
}    

println new JsonBuilder(document).toPrettyString()

打印哪些:

{
    "person": {
        "address": {
            "city": "New York",
            "state": "New York",
            "street": "Third Street"
        },
        "age": 33,
        "name": "Guillaume",
        "pets": [
            {
                "color": "brown",
                "type": "dog"
            },
            {
                "color": "brown",
                "type": "dog"
            }
        ]
    }
}