简体   繁体   English

Groovy-解析字符串化的JSON

[英]Groovy - parse stringified JSON

I have a stringified json looking like this: 我有一个字符串化的json看起来像这样:

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

Which I am trying to parse as a JSON object. 我正在尝试将其解析为JSON对象。

I have tried using JsonSlurper with the following code: 我尝试将JsonSlurper与以下代码结合使用:

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

    object.a

But it failed because of the u : 但是由于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. 因此,这看起来像有效的Python,而不是JSON。 Assuming you control the Python program that has passed you the data, do something like the following in that program: 假设您控制传递数据的Python程序,请在该程序中执行以下操作:

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? 如果您不控制Python,或者从bash管道调用Groovy脚本,那么可以将以下步骤添加到管道中吗?

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... 在最后一种情况下,您可以从Groovy调用那行Python。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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