This is the json data structure used in flutter
flutter: {
"members": [
{
"firstName": "Michael"
},
{
"firstName": "Jennifer"
},
{
"firstName": "Lisa"
}
]
}
To access the above data I used the below code
var parsedData = json.decode(state.successResponse);
var name = parsedData['members'];
I am not able to access the inner field of firstName in the above json.
How should I do that?
Since members is JSON Array you can convert it to dart List type and then you can operate on the list (adding, removing, accessing elements by index).
You can do something like this -
List members = parsedData['members'];
//You can access members by index
print(members[1]); //prints {firstName: Jennifer}
print(members[1]['firstName']); //prints Jennifer
//Or you can iterate over the list
members.forEach((member){
print(member['firstName']);
});
Hope this helps!
Related
I have a json file like this:
{
"company1":
{
"id": "123456",
"created": "2019"
},
"company2":
{
"id": "223424",
"created": "2020"
}
}
I'm using cpprest library for handle json data and REST API.
for accessing the id and created field in above json we can easily do this:
jsonObject[U("company1")].at(U("created")).as_string()
But how i can find company name, if i don't have them or how i can get created and id value without knowing company names?
I didn't find it on their wiki also.
It was straightforward!
For finding Company name iterate over JsonObject and then key value is the company names. Source
const json::value& v = previousTask.get();
for (auto iter = v.as_object.cbegin(); iter != v.as_object.cend(); ++iter)
{
const json::value &key = iter->first;
}
I have the following Json file and I need to compare data to see how many times each value repeat itself. The problem is, I have no idea about handling Json. I don't want the answer to my exercise, I want to know how to access the data. Json:
{
"tickets": [
{
"ticket_id": 0,
"timestamp": "2016/05/26 04:47:02",
"file_hash": "c9d4e03c5632416f",
"src_ip": "6.19.128.119",
"dst_ip": "145.231.76.44"
},
{
"ticket_id": 1,
"timestamp": "2017/05/28 16:14:22",
"file_hash": "ce8a056490a3fd3c",
"src_ip": "100.139.125.30",
"dst_ip": "145.231.76.44"
},
{
"ticket_id": 2,
"timestamp": "2015/08/23 03:27:10",
"file_hash": "d17f572496f48a11",
"src_ip": "67.153.41.75",
"dst_ip": "239.168.56.243"
},
{
"ticket_id": 3,
"timestamp": "2016/02/26 14:01:33",
"file_hash": "3b28f2abc966a386",
"src_ip": "6.19.128.119",
"dst_ip": "137.164.166.84"
},
]
}
If this is a string representation of the object, first you need to set a variable and parse the string to have object you can work with.
jsonString = "{...your json string...}"
Then parse the string,
import json
jsonObject = json.loads(jsonString)
To access the data within it's like any other js object. Example :
jsonObject.tickets[0].timestamp
would return "2016/05/26 04:47:02"
tickets is the key within the jsonObject, 0 is the index of the first object in the list of tickets.
You can use the built-in "json" library to parse your file into an object:
import json
f = open('myfile.json','r')
tickets = json.loads(f.read())
This will return a "tickets" object. How you "compare" (or what exactly you compare) is up to you.
I have an AppSync GraphQL API that makes a Query to a DynamoDB and returns a JSON String, however in my Response Mapping Template I use the built-in $util.parseJson() function as listed here - but I'm still returned a JSON string in the Query window and when requesting the data in my React app.
Schema file, I have an ordinary ID & Address field that is of type AWSJSON.
type Venue {
id: ID!
address: AWSJSON
}
When running a mutation, I usually run the address object through a quick JSON.stringify(addressObj) and that formats the object as a string with the \"\" escaped, meaning that it can be inserted into DynamoDB.
Request Mapping template
{
"version": "2017-02-28",
"operation": "GetItem",
"key": {
"id": $util.dynamodb.toDynamoDBJson($ctx.args.id),
}
}
Response Mapping template
#set($result = $ctx.result)
## address - parse back to JSON
#set($result.address = $util.parseJson($ctx.result.address))
## Return the result
$util.toJson($result)
The idea to create a new variable and then assign the value to the parseJSON value was taken from How return JSON object from DynamoDB with appsync?. So, as seen below, I am parsing the value through what seems to be the correct method to turn it from stringified JSON, to an object - but it doesn't appear to work.
The current response:
{
"data": {
"getVenue": {
"id": "31538150",
"address": "{\"lng\":-1.54511300000001,\"postcode\":\"LS1 5DL\",\"short\":\"New Station St., LS1\",\"lat\":53.795231,\"full\":\"16 New Station St, Leeds LS1 5DL, UK\"}"
}
}
}
Whereas the response that I am wanting is...
{
"data": {
"getVenue": {
"id": "31538150",
"address": { "lng": -1.54511300000001, "postcode": "LS1 5DL", "short": "New Station St., LS1", "lat": 53.795231, "full": "16 New Station St, Leeds LS1 5DL, UK" }
}
}
}
Any help is greatly appreciated!
Old question but thought I would add some notes...
AWSJSON is a string value that will be parsed into DynamoDB as JSON and stringified again on fetching.
So AppSync expects a string (stringified JSON) for inputs and will return a string that can be parsed with JSON.parse.
However this data is parsed before storing in DynamoDB. So of you query DynamoDB separately than through AppSync then you can query it like it was an object. Same with inputing directly into DynamoDB.
The only way to get JSON in the AppSync result is to define each and every field in GraphQL. Sometimes this can be achieved by restructuring data. For example instead of storing:
{
bob: { age: 34 },
igor: { age: 124 }
}
Which would need to be stringified as an AWSJSON field. It can however be restructured like this:
[{
name: 'bob',
age: 34
}, {
name: 'igor',
age: 123
}]
Which can be defined in GraphQL as something like this:
type User {
age: Int,
name: String
}
So that one can now extract specific value such as age from the GraphQL without involving and JSON parse/stringify.
I have a JSON file that contains a JSON Array
test.json
[
{ "Name": "Bob" },
{ "Age": "37" },
{ "DOB": "12/01/1985"}
]
I would like to test each respective element in the JSON array against an endpoint to observe the performance of the system against unique payloads
currently I have
testService.scala
val payload = jsonFile("test.json").circular
val httpProtocol = http
.baseURL("http://test.com")
.headers(Map("Content-Type" -> "application/json"))
val scn = scenario("Test Service")
.feed(payload)
.exec(http("test_request")
.post("/v1/test")
.queryParam("key", "123")
.body()
I am not able to pass each respective child from the payload in the .body() as a JSON
The Gatling Docs say that the JSON Feeder loads the each element of the Array into a record collection
https://gatling.io/docs/2.3/session/feeder/
i.e:
record1: Map("id" -> 19434, "foo" -> 1)
record2: Map("id" -> 19435, "foo" -> 2)
and set the body to .body(StringBody("""[{"id": ${id}}]"""))
The issue is I have different keys (Name,Age,DOB) and I'd like each one to be a different request sent.
.body(StringBody("""[{"KEY_NAME_HERE": ${KEY_NAME_HERE}}]"""))
How do I achieve this?
This is how i am doing:-
company_users.json.json
[
{
"env":"dev",
"userName": "a#test.com",
"password": "Qwerty!12345678"
},
{
"env":"sit",
"userName": "b#test.com",
"password": "Qwerty!12345678"
},
{
"env":"uat",
"userName": "c#test.com",
"password": "Qwerty!12345678"
},
{
"env":"prod",
"userName": "d#test.com",
"password": "Qwerty!12345678"
}
]
Working Code Snippet:
val jsonFileFeederCompany = jsonFile("data/company_users.json").circular
val get_company_user_token = http("Get Company Tokens")
.post(gwt_token_url)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.body(StringBody(
"""{
"env": "${env}",
"userName": "${userName}",
"password": "${password}"
}"""
)).asJson
.check(status.is(200))
.check(jsonPath("$.jwtToken").saveAs("jwtToken"))
val getCompanyUsersGwtToken = scenario("Create Company GWT token Scenario")
.feed(GetTokenRequest.jsonFileFeederCompany)
.exec(GetTokenRequest.get_company_user_token).exitHereIfFailed
This will read each array[position] from json and replace the values in request, to fetch security tokens from different env.
Hope this helps.
Regards,
Vikram Pathania
In your case JSONs from that array are loaded one by one, and since each first level key from that JSON will be saved as session attribute then users in your simulation end up with just 1 of 3 attributes depending which JSON was used. This way you can't (or to be precise can't easily) build body string. In that simple case it would be better to have JSONs with same fields, so you can rely on them when building request payload. Fe. you can place payload key and value in separate fields:
[
{
"key":"Name",
"value":"Bob"
},
{
"key":"Age",
"value":"37"
},
{
"key":"DOB",
"value":"12/01/1985"
},
]
This way for each user in simulation you will have two attributes key and value so you will be able to construct payload like:
.body(StringBody("""{"${key}": "${value}"}"""))
Of course this will work only in that simple case you described and with string-only values in JSONs. If your final goal is to make something more complex please provide real-life example.
How do i convert json text file to..
var nested_obj = { pic: "jaedongImage", name: "ananth", team: "evil geniuses", server: "NA" };
My text file as below..
{
"data": [
{
"pic": "jaedongImage,"
"name": "ananth",
"team": "evil geniuses",
"server": "N/A"
}
]
}
It's unclear what you're asking, but: The JSON depicts an object with one property, data, which refers to an array. The array has one entry, which is the object you wanted. From your initial code sample, it looks like you're using JavaScript, so: Assuming you're receiving text (a string) in JSON format, you would parse it using JSON.parse, and then get at that object via data[0]:
var obj = JSON.parse(text);
var pic = obj.data[0];