Python accessing element inside array inside json - json

Can someone help me to access myapp from below json using python, please ?
{
"Data": {
"Name": "myname",
"AccountName": "test",
"classic": [
{
"cName": "mycname",
"tags": ["tag1", "tag2"],
"Version": "1.14.10",
"app": "myapp"
}
]
}
}

Use json.load for reading a file or json.loads for a string.
data_dict = json.loads(your_data)
print(data_dict["Data"]["classic"][0]["app"])

Use json loads to parse a json string and json dumps for stringifying the json to a json string
Here in your case you will need json loads
input = {
"Data": {
"Name": "myname",
"AccountName": "test",
"classic": [
{
"cName": "mycname",
"tags": ["tag1", "tag2"],
"Version": "1.14.10",
"app": "myapp"
}
]
}
}
parsed_input = json.loads(input)
output = parsed_input["Data"]["classic"][0]["app"]
print(output)

You can use json library for the same.
input_json= {
"Data": {
"Name": "myname",
"AccountName": "test",
"classic": [
{
"cName": "mycname",
"tags": ["tag1", "tag2"],
"Version": "1.14.10",
"app": "myapp"
}
]
}
}
data = json.loads(input_json)
result=data["Data"]["classic"][0]["app"])

Related

How to feed a value into a field in a json array in Gatling?

I am using Gatling to test an API that accepts a json body like below:
{
"data": {
"fields": [
{
"rank": 1
},
{
"name": "Jack"
}
]
}
}
I have created a file feeder.json that contains array of json objects like above.
Below is the feeder.json
[
{
"data": {
"fields": [
{
"rank": 1
},
{
"name": "Jack"
}
]
}
}
]
I have created another file template.txt that contains the template of above json.
Below is the template.txt
{
"data": {
"fields": [
{
"rank": ${data.fields[0].rank} //this is not working
},
{
"name": "Jack"
}
]
}
}
val jsonFeeder = jsonFile("feeder.json").circular
scenario("Test scenario")
.feed(jsonFeeder)
.exec(http("API call test")
.post("/data")
.body(ElFileBody("template.txt"))
.asJson
.check(status is 200))
I am feeding the feeder.json and also sending json body from template.json. The 'rank' property values should get set from feeder into the json body. But I am getting an error 'Map named 'data' does not contain key 'fields[0]'. Stuck with this.
Access by index syntax uses parens, not square braces.
#{data.fields(0).rank}

Extract nested JSON array response object using JS Lodash in Postman

I want to learn how to use Lodash to extract variables from a JSON response because the traditional methods explained on other Postman questions do not explain an easy way to do this as I used to do it with json path in Jmeter.
I need to translate the following json paths to a Lodash expression that returns the same values as this JSON paths
1. FlightSegmentsItinerary[*].Flights[*].Key
2. $..Flights[*].Key
3. Travelers[*].[?(#.TypeCode == "INF")].FirstName (returns the name of the passangers whose type code are == "INF")
JSON Response:
{
"Travelers": [
{
"TypeCode": "ADT",
"FirstName": "FULANO",
"Surname": "LAZARO",
"Key": "1.1"
},
{
"TypeCode": "INF",
"FirstName": "MENGANO",
"Surname": "XULO",
"Key": "2.2"
}
],
"FlightSegmentsItinerary": [
{
"Flights": [
{
"Key": "1"
},
{
"Key": "2"
}
]
}
]
}
So far I was able to extract the travelers Keys (Travelers[*].Key) using this:
var jsonData = pm.response.json();
var travelerKeys = _.map(jsonData.Travelers, 'Key');
console.log("travelerKeys: " + travelerKeys);
Output: travelerKeys: 1.1,2.2
As you can see, the JSON path:
Travelers[*].Key
Looks like this in Lodash:
var travelerKeys = _.map(jsonData.Travelers, 'Key');
for this case.
var jsonData = {
"Travelers": [{
"TypeCode": "ADT",
"FirstName": "FULANO",
"Surname": "LAZARO",
"Key": "1.1"
},
{
"TypeCode": "INF",
"FirstName": "MENGANO",
"Surname": "XULO",
"Key": "2.2"
}
],
"FlightSegmentsItinerary": [{
"Flights": [{
"Key": "1"
},
{
"Key": "2"
}
]
}]
}
// 1. FlightSegmentsItinerary[*].Flights[*].Key
console.log( _(jsonData.FlightSegmentsItinerary).flatMap('Flights').map('Key') )
//2. $..Flights[*].Key
console.log( _.chain(jsonData).values().flatten().find('Flights').values().flatten().map('Key') )
//3. Travelers[*].[?(#.TypeCode == "INF")].FirstName (returns the name of the passangers whose type code are == "INF")
console.log( _(jsonData.Travelers).filter(['TypeCode', 'INF']).map('FirstName') )
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.11/lodash.min.js"></script>
Another option might be to try JavaScript libraries such as https://github.com/dchester/jsonpath
var jsonData = {
"Travelers": [{
"TypeCode": "ADT",
"FirstName": "FULANO",
"Surname": "LAZARO",
"Key": "1.1"
},
{
"TypeCode": "INF",
"FirstName": "MENGANO",
"Surname": "XULO",
"Key": "2.2"
}
],
"FlightSegmentsItinerary": [{
"Flights": [{
"Key": "1"
},
{
"Key": "2"
}
]
}]
}
console.log(jsonpath.query(jsonData, '$.FlightSegmentsItinerary[*].Flights[*].Key'))
console.log(jsonpath.query(jsonData, '$..Flights[*].Key'))
console.log(jsonpath.query(jsonData, '$.Travelers..[?(#.TypeCode == "INF")].FirstName'))
<script src="https://cdn.jsdelivr.net/npm/jsonpath#1.0.2/jsonpath.min.js"></script>
Because Postman doesn't support fetch and XMLHttpRequest, the jsonpath.min.js file contents can be saved in environment variable, and then eval(pm.environment.get('jsonpath')); before use as described in
https://community.getpostman.com/t/adding-external-libraries-to-postman/1971/4
You have to tell Postman which Sandbox module you going to use using require function(refer below code). The error you get has some issue with Postman few of them works few of them not Here they are talking
and Here is the postman issue tracker
the code I tried and worked for me as
const moment = require('lodash');
var keys = _.chain(obj.Travelers)
.map("Key")
.flatten()
.unique()
.value();
console.log(keys);
output
Array:[]
0 : "1.1"
1 : "2.2"
form more details you can look at
Postman Sandbox API reference
postman-and-lodash-the-perfect-partnership

how to parse the json file and read the json elements in groovy

Hi i am trying to parse the below json file. I tried using jsonsluper and parsed the file. I executed below command. Nothing works.
def test =newjsonslurper().parsetext(organist)
test.resources.each{
println it.resources.metadata. "guid"
println it.resources.entity. "name"
}
This is the json file format
resources: [
{
"metadata" :{
"guid":"cya"
"url": "dummy.test"
},
"entity" :
{
"name": "system"
"status": "active"
}
}
{
"metadata" :
{
"guid":"cya"
"url": "dummy.test"
},
"entity" :
{
"name": "system"
"status": "active"
}
}
]
There were a couple of problems:
JsonSlurper().parseText() expects a String. If you're wanting to parse a file, use something like def response = new JsonSlurper().parse(new File('JsonFile.json'))
The JSON payload is not valid: it's missing a few brackets and commas.
The following code should work:
import groovy.json.JsonSlurper
def test = new JsonSlurper().parseText '''
{"resources": [
{
"metadata": {
"guid": "cya",
"url": "dummy.test"
},
"entity": {
"name": "system",
"status": "active"
}
},
{
"metadata": {
"guid": "cya",
"url": "dummy.test"
},
"entity": {
"name": "system",
"status": "active"
}
}
]}
'''
test.resources.each {
println it.metadata.guid
println it.entity.name
}

Sending the JSON response as array or normal object

I am implementing a restful service where I am getting the pdf names and their ids from the database in the JSON fromat. Which one of the both the convenient JSON resful service response?
First Option:
{
"results": {
"documentNames": [
"test.pdf",
"ireport-ultimate-guide.pdf",
"sending report.pdf",
"Motor Hour.pdf"
],
"documentds": [
21116,
21117,
21118,
21119
]
}
}
Second Option:
{
"results": {
"21116": "test.pdf",
"21117": "ireport-ultimate-guide.pdf",
"21118": "sending report.pdf",
"21119": "Motor Hour.pdf"
}
}
I would use this "third option": The result is a list of object.
{
"result": [{
"id": "21116",
"filename": "test.pdf"
},
{
"id": "21117",
"filename": "ireport-ultimate-guide.pdf"
},
{
"id": "21118",
"filename": "sending report.pdf"
},
{
"id": "21119",
"filename": "Motor Hour.pdf"
}
]
}
because it better models the object structure.
I would create an entity for each document that contains both name and I'd.
[
{"name": "doc_1", "id": 123},
{"name": "doc_2", "id": 456}
]

How to Append JSON Object in already created object in mysql json document

My object is
{
"name":"Testing",
"id": "hcig_3fe7cb00-e936-11e6-af69-a748c8cc89ad",
"belongsTo": {
"id": "69616d26-c3bb-405c-8c84-c51c091524b2",
"name": "test"
},
"locatedAt": {
"id": "49616d26-c3bb-405c-8c84-c51c091524b2",
"name":"Test"
} }
I want to merge one more object like
"obj":[{
"a": 123
}}
With the help of JSON_MERGE in mysql document store i am able to add object.
But it looks likes
{
"name":"Tester",
"id": "hcig_3fe7cb00-e936-11e6-af69-a748c8cc89ad",
"belongsTo": {
"id": "69616d26-c3bb-405c-8c84-c51c091524b2",
"name": "test"
},
"locatedAt": {
"id": "49616d26-c3bb-405c-8c84-c51c091524b2",
"name":"Test"
},{
"obj":[{
"a": 123
}]
}}
I want my object to be as
{
"name": "Tester",
"id": "hcig_3fe7cb00-e936-11e6-af69-a748c8cc89ad",
"belongsTo": {
"id": "69616d26-c3bb-405c-8c84-c51c091524b2",
"name": "test"
},
"locatedAt": {
"id": "49616d26-c3bb-405c-8c84-c51c091524b2",
"name": "Test"
},
"obj": [{
"a": 123
}]}
Any idea on how to add object as above manner using JSON Functions in mysql ??
Use lodash for a recursive deep copy - https://lodash.com/
lodash.merge(targetObj, sourceObj);
Or if you have programmatic access:
targetObj.obj = sourceObj;