Get a object from json based on a specific value - json

I have a json string. I need to get a specific object based on an id value. Suppose I entered 2, then I want {"id":"2","name":"def"} as the result. I want this to be done in java class.
[
{"id":"1",
"name":"abc"},
{"id":"2",
"name":"def"}
]

Put the Objects in the Array for better manipulation..!!!
JSONObject data = new JSONObject(YOUR_JSON);
JSONArray data_Values=data.getJSONArray(values);
int n=2;// Entered ID
for(int i=0;i<=data_Values.length();i++)
{
if(n==data_Values.getInt("id"))
{
id=data_Values.getInt("id");
name=data_Values.getString("name");
}
}
JSON Data
{
"Values": [
{
"id": "1",
"name": "ABC"
},
{
"id": "2",
"name": "EFG"
},
{
"id": "3",
"name": "HIJ"
}
]
}

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}

parsing json object with number as its key fields?

I'm trying to parse json into kotlin objects but the problem is that its key fields are numbers any idea how can parse them , I've tried serialized name but still facing problem.
The json response looks like this :
{
"Id": [{
"1": {
"name": "name1",
"class": "11a"
}
},
{
"2": {
"name": "name2",
"class": "11b"
}
}
]
}
I'm using gson and the main thing i'm trying to do is to store this number fields as some other string objects.
You can parse them into a list of maps, then "map" those to your data classes instead:
val input = """{
"Id": [{
"1": {
"name": "name1",
"class": "11a"
}
},
{
"2": {
"name": "name2",
"class": "11b"
}
}
]
}"""
val gson = Gson()
val parsed: Map<String, List<Map<String, Any>>> =
gson.fromJson(input, (object : TypeToken<Map<String, List<Map<String, Any>>>>(){}).type)
println(parsed["Id"]?.get(0)?.get("1")) // {name=name1, class=11a}
It will have some nasty generic signature, though.
If you're working with Kotlin, take a look at Klaxon, it will improve your experience.

JSON transformation in node.js

I want to transform my data from one json structure to another. What is the best way to do it?
Here is my original resource (customer) structure is:
{
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
I want to change it to:
{
"id": "123",
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
Keeping in mind that I might have an array of resources(customers) being returned in GET /customers cases. I want to change that to an array of new data type.
If customer object is array of object then below will help you to get desire format result
var result = customerObj.map(x => {
return {
id: x.id,
name: x.data.name,
status: x.data.status,
contacts: x.data.contacts
};
});
here I have used Object.assign() it will be helpful to you
var arr={
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
arr=Object.assign(arr,arr.data);
delete arr['data'];
console.log(arr);
You have to Json.parse the json into variable, and then loop through the array of objects, changes the object to the new format, and then JSON.stringify the array back to json.
Example code
function formatter(oldFormat) {
Object.assign(oldFormat, oldFormat.data);
delete oldFormat.data;
}
let parsedData = JSON.parse(Oldjson);
//Take care for array of results or single result
if (parsedData instanceof Array) {
parsedData.map(customer => formtter(customer));
} else {
formatter(parsedData);
}
let newJson = JSON.stringify(parsedData);
console.log(newJson);
Edit
I made the formatter function cleaner by using Kalaiselvan A code

RestKit mapKeyOfNestedDictionaryToAttribute with array

I have a JSON response which looks like the sample below. I have added some comments // to emphasize my question.
I have no idea how to build the RKObjectMapping for the dynamic keys ("FieldNameA", "FieldNameB" - this could be anything) in combination with the array as the value. Each item of the array is of a type FieldResult.
I already learned how to handle varying key names here, but I don't get how I could properly map the array item type.
{
"result": {
"status": "FAILURE",
"details": {
"FieldNameA": [ // dynamic key name here, array of objects as a value
{
"details": {
"errorName": "InvalidField",
"errorNumber": 123
},
"status": "FAILURE"
}
],
"FieldNameB": [ // multiple values in this array, all of same type FieldResult
{
"details": {
"errorName": "UpdateRequired",
"errorNumber": 321
},
"status": "UPDATE_REQUIRED",
"suggestion": {
"update": "UpdatedInputValue"
}
},
{
"details": {
"errorName": "TooShort",
"errorNumber": 1
},
"status": "FAILURE"
}
]
}
}
}
Any help appreciated!

json object accessing

i know its very simple thing but i m stucked on it
i have json variable with data as follow
var jsonText =
'[ { "user": [ { "Gender": "M", "Minage": "19", "Maxage": "30", "MaritalStatusId":"0", }]
},
{ "user":[ { "maritialtype": "Does not matter" }]
},
{ "user": [ { "Value": "No" }]
} ]';
var jsonObject = JSON.parse(jsonText);
now i can access gender as jsonObject[0].user[0].Gender
but i'm not able to access maritialtype and Value
For maritialtype:
jsonObject[1].user[0].maritialtype
For Value:
jsonObject[2].user[0].Value
Because you have an array of three objects, user, which is an array or one object. It's kind of a weird structure.