能否使用Groovy将非标准类JSON格式转换为标准JSON格式?
Absolutely! You can convert this non-standard JSON-like string to valid JSON using Groovy, and there are a couple of straightforward approaches to do it. Here are two reliable methods:
Method 1: Regex-Based Replacement (Safer for Untrusted Input)
This approach uses regular expressions to directly transform the non-standard string into valid JSON without executing any dynamic code. It works perfectly for your specific input structure:
def input = '{ id=102, brand=Disha, book=[{ slr=EFTR, description=Grammer, data=TYR, rate=true, numberOfPages=345, maxAllowed=12, currentPage=345 }, { slr=EFRE, description=English, data=TYR, rate=true, numberOfPages=345, maxAllowed=12, currentPage=345 }] }' // Step 1: Quote all string values (skip booleans and numbers) def withQuotedStrings = input.replaceAll(/=(\b(?!true|false)\w+\b)([,}\]])/, '="$1"$2') // Step 2: Wrap all keys in double quotes def withQuotedKeys = withQuotedStrings.replaceAll(/(\w+)=/, '"$1": ') // Step 3: Convert specific numeric values to strings (id and maxAllowed) def standardJson = withQuotedKeys.replaceAll(/"id":(\d+)/, '"id":"$1"') .replaceAll(/"maxAllowed":(\d+)/, '"maxAllowed":"$1"') println standardJson
How it works:
- Step 1: Quotes any value that's a word (letters/underscores) but not
trueorfalse(your string values likeDisha,EFTR). - Step 2: Adds double quotes around all keys (like
id→"id"). - Step 3: Converts the numeric values of
idandmaxAllowedto strings while leaving other numbers (likenumberOfPages) as numeric types.
Method 2: Groovy Map Parsing (More Flexible for Complex Structures)
If your input structure might vary or you need to manipulate the data further, you can convert the non-standard string into a Groovy map, adjust the types, then serialize it back to JSON:
import groovy.json.JsonBuilder def input = '{ id=102, brand=Disha, book=[{ slr=EFTR, description=Grammer, data=TYR, rate=true, numberOfPages=345, maxAllowed=12, currentPage=345 }, { slr=EFRE, description=English, data=TYR, rate=true, numberOfPages=345, maxAllowed=12, currentPage=345 }] }' // Convert to Groovy map literal syntax def groovyLiteral = input.replaceAll(/=(\b(?!true|false)\w+\b)([,}\]])/, '="$1"$2') .replaceAll(/=/, ':') .replaceAll(/\{/, '[') .replaceAll(/\}/, ']') // Parse into a Groovy map (note: Eval.me is safe only for trusted input) def dataMap = Eval.me(groovyLiteral) // Adjust data types as needed dataMap.id = dataMap.id.toString() dataMap.book.each { book -> book.maxAllowed = book.maxAllowed.toString() } // Serialize to standard JSON def jsonBuilder = new JsonBuilder(dataMap) def standardJson = jsonBuilder.toPrettyString() println standardJson
Notes:
Eval.meexecutes the string as Groovy code, so only use this if you trust the input source.- This method gives you full control to modify the data structure or types before converting to JSON.
Both methods will produce the exact standard JSON format you requested.
内容的提问来源于stack exchange,提问作者avidCoder
相关产品推荐
相关产品推荐

