Parse string into JSON

2019-07-31 14:50发布

问题:

I have an array of objects $arr and an object has a property named as jsonData which contains json data in a string, how to parse that string to actual JSON object and retrieve lets say value for key name? I tried this:

#foreach ($obj in $arr)
    #set ($jsonData = "#evaluate(${obj.jsonData})")
    $jsonData.get("name")  ## <-- not working
#end

回答1:

If anyone using velocity in AWS API Gateway ends up here, you can use AWS'

$util.parseJson() to covert a string to JSON.

Make sure you note if your string is using single or double quotes. You may need to use $util.escapeJavaScipt.replaceAll() before parsing the string.



回答2:

g.o.a.t, your answer is almost correct; there's a slight typo in that you want to use $util.parseJson(), not $utils.parseJson(). Even so, it helped me tremendously, so thank you. I would have commented on your post, but I don't have enough rep. :(



回答3:

Fixed it like this:

#foreach ($obj in $arr)
    #set( $jsonData = '#set( $jsonData = ' + $obj.jsonData + ' )' )
    #evaluate ($jsonData)
    $jsonData.get("name")  ##<-- works now
#end

I was using velocity 1.7



回答4:

This is mainly AWS lambda (in python) response template related.. so.. if you want to return custom response code with json it is easy to return JSON in node js but when it comes to python as per i know, we cant raise dict as a value. So.. this may help. If you are doing like..

raise Exception({"responseCode": 400, "response": "missing :\"recipientCount\""})

It will throw exception in errorMessage key and value as a string.

To overcome this..

Add response code 400 in Method Response

regExp in Integration Response :

.*'responseCode': 400.*

Add Body Mapping Template as application/json:

$util.escapeJavaScript( $input.path('$.errorMessage')).replaceAll("\\'",'\"')

Make sure you are not using single quotes in value in exception string.

Wrong:

raise Exception({"responseCode": 400, "response": "missing :'recipientCount'"})

Right:

raise Exception({"responseCode": 400, "response": "missing :\"recipientCount\""})

I know it is not best solution... but this is the only solution i have found. Feel free if you have better solution.