parsing nested json data - access directly to a member - html

I have json data like
data = {
"id":1,
"name":"abc",
"address": {
"items":[
"streetName":"cde",
"streetId":"SID"
]
}
}
How can i access directly to the streetName Value ?

Your json is actually invalid. If you have control over the json generation, first change it to this:
data = {
"id": 1,
"name": "abc",
"address": {
"items": [{
"streetName": "cde",
"streetId": "SID"
}]
}
}
Notice the additional braces around streetName and streetId. Then, to access streetName, do this:
var streetName = data.address.items[0].streetName;

Related

How do i get a specific data from responseBody on postman

I'm trying to set an environment variable using the following:
var data = JSON.parse(responseBody);
pm.environment.set("petId", data.id);
And this is what is in my response:
{
"id": 9222999990497629102,
"category": {
"id": 0,
"name": "dog"
},
"name": "Brutus",
"photoUrls": [
"http://placeimg.com/640/480"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}
But somehow my environment looks like this:
"petId": "9222999990497629000"
I don't where from where I'm getting these last zeros on my variable.
pm.environment.set("petId", JSON.parse(pm.response.text().replace(/"id":[\s]*([\d]+),/,'"id":"$1",')).id);
As the id is a big int greator than MAX_SAFE_Integer , the response will be rounded when parsed as JSON. It is a javascript behavior.
You can enclose it with double quotes. After that extract that id.
now if you want to convert id to number use BigInt
let id = JSON.parse(pm.response.text().replace(/"id":[\s]*([\d]+),/,'"id":"$1",')).id
id = BigInt(id)
console.log(id)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

How to add a field to an existing JSON in Velocity?

I have a JSON coming from a request body and I'm trying to use VTL to map it by adding an additional field to it. The request body looks like this:
{
"name": "John",
"age": 20,
"address": {
"street": "Albert's Street",
"City": "Test City"
}
}
In AWS, I'm trying to map this request body to have an additional field which is coming from a parameter in the URL path to become this:
{
"name": "John",
"age": 20,
"address": {
"street": "Albert's Street",
"City": "Test City"
},
"operation": "$input.params('path.operation')"
}
I have tried looping through with something like this but it doesn't work very well:
#set($allParams = $input.path('$'))
{
#foreach($type in $allParams.keySet())
#set($params = $allParams.get($type))
"$type" : {
#foreach($paramName in $params.keySet())
"$paramName" : "$util.escapeJavaScript($params.get($paramName))"
#if($foreach.hasNext),#end
#end
}
#if($foreach.hasNext),#end
#end
}
Moreover, this only works for those with 2 levels in the JSON. It doesn't work for those at the first level of the JSON or if I happen to have more than 2 levels in the JSON payload.
All I need is simply appending one more field into the existing request body of a JSON payload. How can I do that in Velocity?
You can add a operation property to the input JSON like this:
#set ($input.path('$').operation = 'example')
$input.json('$')
The above results in the following for your example:
{
"name": "John",
"age": 20,
"address": {
"street": "Albert's Street",
"City": "Test City"
},
"operation": "example"
}
Of course, you can use a value from params instead of 'example'.
By the way, consider running the param through $util.escapeJavaScript for added security.

Find specific value in a large json file

I've a simple json array similar to the below. I'd like to find the record that contain a matching value, say for example name == jack.
{
"data": [
{
"Record": {
"attributes": {
"name": "Jack",
"age": "38",
"description": "1234",
}
}
}
]
}
Below python code works but it is very slow. Is there any way to get the results quicker?
with open('records.json') as f:
input_dict = json.load(f)
input_var = input_dict["data"]
for i in input_var:
if i["Record"]["attributes"]["name"] == "Jack":
print(i["Record"]["attributes"])
break

Groovy - Parse JSON where only certain values exists in response

I am trying to parse a JSON response that has repeating objects with JsonSlurper to compare to a JDBC query. However, I only want to compare objects where a certain values exist within that object.
If I had a response that looks like this, how would I only parse the objects where the country equals USA or Canada, therefore ignoring anything else?
{
"info": [{
"name": "John Smith",
"phone": "2125557878",
"country": {
"value": "USA"
}
},
{
"name": "Jane Smith",
"phone": "2125551212",
"country": {
"value": "USA"
}
},
{
"name": "Bob Jones",
"phone": "4165558714",
"country": {
"value": "Canada"
}
},
{
"name": "George Tucker",
"phone": "4454547171",
"country": {
"value": "UK"
}
},
{
"name": "Jean Normand",
"phone": "4454547171",
"country": {
"value": "France"
}
}]
}
This is what I have in groovy:
def jsonResponse = context.expand('${RESTRequest#Response}')
def parsedJson = new JsonSlurper().parseText(jsonResponse)
def info = parsedJson.info
def jsonDataObjects = []
info.each { json ->
jsonDataObjects.add(Model.buildJSONData(json))
}
I am building a collection of the elements that I need to compare to a database. How do I only add to that collection where the info.country.value = USA or Canada?
I tried using .findAll like this just to test if I could get it to filter by just one of the countries:
def info = parsedJson.info.country.findAll{it.value == "USA"}
But, when I do that, only the value field is kept. I lose the name and phone from the parse.
Thanks in advance for any assistance.
Did you try
def info = parsedJson.info.findAll{it.country.value == "USA"}
?

json request into string

I have the following json structure:
{
"data": [
{
"number": 123,
"animal": "mush"
},
{
"number": "123",
"animal": ""
}
],
"animal_id": 1
}
How can I save it as a string?
It varies by language, but in JavaScript (which might be likely used in your case), JSON.stringify does this job.