简体   繁体   中英

Groovy - parse stringified JSON

I have a stringified json looking like this:

{u'a': u'1', u'b': 2, u'c': 3 }

Which I am trying to parse as a JSON object.

I have tried using JsonSlurper with the following code:

    def jsonSlurper = new JsonSlurper()
    def object = jsonSlurper.parseText(param)

    object.a

But it failed because of the u :

Caused by: groovy.json.JsonException: expecting '}' or ',' but got current char 'u' with an int value of 117

The current character read is 'u' with an int value of 117
expecting '}' or ',' but got current char 'u' with an int value of 117
line number 1
index number 1
{a': u'1', u'b': 2, u'c': 3}

How can I parse this string?

Many thanks

So this looks like valid Python, not JSON. Assuming you control the Python program that has passed you the data, do something like the following in that program:

import json
json.dumps( {u'a': u'1', u'b': 2, u'c': 3 } )

if you don't control the Python, if you're calling your Groovy script from a bash pipeline, can you add the following step to your pipeline?

echo "{u'a': u'1', u'b': 2, u'c': 3 }" | python -c "import json, sys, fileinput; print json.dumps( eval( (open(sys.argv[1] ) if sys.argv[1:] else sys.stdin).read())) "

In last case you could call that line of Python from Groovy...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM