JMETER – 使用JsonBuilder格式化JSON

huangapple go评论72阅读模式
英文:

JMETER - Formatting JSON with JsonBuilder

问题

抱歉,我无法访问外部链接或执行代码,但我可以为您提供如何在现有的Groovy代码中将所需的对象添加到最终JSON中的指导:

要将额外的对象添加到最终JSON中,您可以在生成books数组后,创建一个包含您所需对象的Map,并将其添加到最终的JSON结构中。以下是一种修改代码的方法:

def arraySize = vars.entrySet().findAll { entry -> entry.getKey().startsWith('isbn_') }.size()

def books = []

1.upto(arraySize, {index ->
    books.add([publisher: vars.get('publisherName'),
               ISBN: vars.get('isbn_' + index),
               Price: vars.get('price_' + index),
               Publisher: vars.get('publisher_' + index),
               "Static Value that doesn't change": 100
    ])
})

// 创建您要添加的额外对象
def extraObject = [
    publisher: vars.get('publisherName'), // 这里使用与数组中相同的值
    ISBN: vars.get('your_extra_isbn'), // 替换为您的额外ISBN变量
    Price: vars.get('your_extra_price'), // 替换为您的额外价格变量
    Publisher: vars.get('your_extra_publisher'), // 替换为您的额外出版商变量
    "Static Value that will be the same for all items": 100
]

// 创建最终的JSON结构,将额外对象添加到books数组后面
def finalJson = new groovy.json.JsonBuilder([
    books: books + [extraObject], // 将额外对象添加到数组末尾
    meta: [
        tag: [
            searchNumber: vars.get('searchNo')
        ]
    ]
]).toPrettyString()

log.info(finalJson)

请注意,上述代码中的your_extra_isbnyour_extra_priceyour_extra_publisher 应替换为您要添加的额外对象的变量名称。这将创建一个包含额外对象的最终JSON,并在books数组的末尾添加它。

英文:

Hello I previously asked how to dynamically generate a json array using Groovy here:

https://stackoverflow.com/questions/76569179/jmeter-populate-a-json-request-for-all-items-in-an-array

The provided solution worked great, however I need to add an additional object after the final item in the array. Because the toprettystring formats the array I am unsure how to insert the object into the final result.

Here is an example of the final JSON:

{
 "books": [
        {
            "publisher": ${publisherName}, //variable but it's the same for all items in this request
            "ISBN": ${isbn_1},  //the next three are from from 3 different arrays 
            "Price": ${price_1},
            "Publisher": ${publisher_1},
            "Static Value that doesn't change": 100
       
        },

        {
            "publisher": ${publisherName}, //variable but it's the same for all items in this request
            "ISBN": ${isbn_2},  //the next three are from from 3 different arrays 
            "Price": ${price_2},
            "Publisher": ${publisher_2},
            "Static Value that will be the same for all items": 100
       
        },
        
    ],
    "meta": {
        "tag": {
            "searchNumber": ${searchNo}
        }
    }
}

The solution for the previous question was to use a JSR223 Preprocessor and generate it as follows:

def arraySize = vars.entrySet().findAll { entry -> entry.getKey().startsWith('isbn_') }.size()

def books = []

1.upto(arraySize, {index ->
    books.add([publisher:vars.get('publisherName'),
               ISBN: vars.get('isbn_' + index),
               Price: vars.get('price_' + index),
               Publisher:vars.get('publisher_' + index),
               "Static Value that doesn't change": 100
    ])
})

log.info(new groovy.json.JsonBuilder([books:books]).toPrettyString())

How could I modify this to enter the above object into the final JSON?

答案1

得分: 1

你的最终结果在这里形成:

log.info(new groovy.json.JsonBuilder([books: books]).toPrettyString())

只需将所需字段添加到此映射中:[books: books]

例如,替换最后一行:

def searchNo = ...
def result = [
    books: books,
    meta: [
        tag: [searchNumber: searchNo]
    ]
]
log.info(new groovy.json.JsonBuilder(result).toPrettyString())
英文:

your final result formed here:

log.info(new groovy.json.JsonBuilder([books:books]).toPrettyString())

just add required fields into this map: [books:books]

for example instead of last line:

def searchNo = ...
def result=[
    books: books,
    meta: [
        tag: [searchNumber: searchNo]
    ]
]
log.info(new groovy.json.JsonBuilder(result).toPrettyString())

答案2

得分: 1

请按以下方式修改您的代码:

def arraySize = vars.entrySet().findAll { entry -> entry.getKey().startsWith('isbn_') }.size()

def request = [:]

def books = []

1.upto(arraySize, { index ->
    books.add([publisher                         : vars.get('publisherName'),
               ISBN                              : vars.get('isbn_' + index),
               Price                             : vars.get('price_' + index),
               Publisher                         : vars.get('publisher_' + index),
               "Static Value that doesn't change": 100
    ])
})

def meta = [tag: [searchNumber: vars.getObject('searchNo')]]
request.put('books', books)
request.put('meta', meta)
log.info((new groovy.json.JsonBuilder(request).toPrettyString()))

更多信息:


<details>
<summary>英文:</summary>

Amend your code as follows:

    def arraySize = vars.entrySet().findAll { entry -&gt; entry.getKey().startsWith(&#39;isbn_&#39;) }.size()
    
    def request = [:]
    
    def books = []
    
    1.upto(arraySize, { index -&gt;
        books.add([publisher                         : vars.get(&#39;publisherName&#39;),
                   ISBN                              : vars.get(&#39;isbn_&#39; + index),
                   Price                             : vars.get(&#39;price_&#39; + index),
                   Publisher                         : vars.get(&#39;publisher_&#39; + index),
                   &quot;Static Value that doesn&#39;t change&quot;: 100
        ])
    })
    
    def meta = [tag: [searchNumber: vars.getObject(&#39;searchNo&#39;)]]
    request.put(&#39;books&#39;, books)
    request.put(&#39;meta&#39;, meta)
    log.info((new groovy.json.JsonBuilder(request).toPrettyString()))

More information:

 - [Apache Groovy: Parsing and producing JSON][1]
 - [Apache Groovy: What Is Groovy Used For?][2]


  [1]: https://groovy-lang.org/processing-json.html
  [2]: https://www.blazemeter.com/blog/apache-groovy

</details>



huangapple
  • 本文由 发表于 2023年7月18日 03:00:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定