I'm using SwiftyJSON to create a data dictionary in JSON.
Now I want to arrange one of the sub dictionaries called fb_friends by friend_health_points.
I tried using Sort or any other manipulation but I get String/JSON errors.
So basically I'm trying to sort it so that 150 health points will be first and 20 will be last in that data dictionary.
This is the data:
var data: JSON = [
"user_id": 7742,
"name": "Bla",
"fb_friends": [
[
"friend_id": 202072,
"friend_name": "Bla Bla",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 50,
],
[
"friend_id": 502333,
"friend_name": "hdfghdfghfdgh",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 150,
],
[
"friend_id": 202072,
"friend_name": "gjhkghjk",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 20,
]
]
This is a solution without third-party libraries
var data = [
"user_id": 7742,
"name": "Bla",
"fb_friends": [
[
"friend_id": 202072,
"friend_name": "Bla Bla",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 50,
],
[
"friend_id": 502333,
"friend_name": "hdfghdfghfdgh",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 150,
],
[
"friend_id": 202072,
"friend_name": "gjhkghjk",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 20,
]
]
]
let friends = (data["fb_friends"] as! [[String:AnyObject]]).sort{ ($0["friend_health_points"] as! Int) > $1["friend_health_points"] as! Int}
data["fb_friends"] = friends
print(data)
let json = JSON(data)
Ok I found the answer, because the object is of type SwiftyJSON I can use arrayValue to extract it to array.
So this will give me back a sorted array of friends.
let fbFriends = data["fb_friends"]
let friendsArray = fbFriends.arrayValue
let sortedFriends = friendsArray.sort { $0["friend_health_points"].doubleValue > $1["friend_health_points"].doubleValue }
Related
I need to convert the following array data to Json in react.
I tried map method, but it is not the correct way. I need key value pair, so that i can pass it to server as json
[
[
"channel",
"s1"
],
[
"category",
"Account 1"
],
[
"accountAdministration",
"Partnership 1"
],
[
"partnershipAccounting",
"1 level Performance issues"
],
[
"requestCategory",
"Research"
],
[
"severity",
"Blocker"
],
[
"activationDate",
"2020-10-29T05:54:00.000Z"
],
[
"managerApproved",
true
]
]
Try using reduce and creating an object:
var arr = []; // your array
var data = arr.reduce((map, item) => {
map[item[0]] = item[1];
return map;
}, {});
The data object will be in the following format:
{
"accountAdministration": "Partnership 1",
"activationDate": "2020-10-29T05:54:00.000Z",
"category": "Account 1",
"channel": "s1",
...
}
Worked with
Object.fromEntries([
[
"channel",
"s1"
],
[
"category",
"Account 1"
],
[
"accountAdministration",
"Partnership 1"
],
[
"partnershipAccounting",
"1 level Performance issues"
],
[
"requestCategory",
"Research"
],
[
"severity",
"Blocker"
],
[
"activationDate",
"2020-10-29T05:54:00.000Z"
],
[
"managerApproved",
true
]
])
I have fetched data from a JSON file.. But when I tried to fetch another data from it, am unable to do so as it is a nested array... I know the solution can arrive easily but this is the first time am trying to loop a JSON file.. so kindly give your inputs.
SampleData = {
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Immortality",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
};
GetJsonData() {
console.log(this.SampleData["powers"]);
for (let i = 0; i < this.SampleData["powers"].length; i++) {
if (this.SampleData["powers"][i].Immortality) {
console.log(this.SampleData.powers[i]);
}
}
}
{name: "Molecule Man", age: 29, secretIdentity: "Dan Jukes", powers: Array(3)}
{name: "Eternal Flame", age: 1000, secretIdentity: "Unknown", powers: Array(3)}
Your code needs to follow the structure of the JSON data; in particular, these are all valid things you could print:
console.log(this.SampleData.squadName);
console.log(this.SampleData.homeTown);
console.log(this.SampleData.members[0].name);
console.log(this.SampleData.members[0].powers[0]);
If you wanted to loop through each member and print their info, that might look like this:
this.SampleData.members.forEach(member => {
let powerString = member.powers.join(', ');
console.log('Name: ' + member.name);
console.log('Age: ' + member.age);
console.log('Powers: ' + powerString);
});
I used a forEach, but you can also use a for (let i = loop.
I'm trying to parse JSON which is like below:
"price": [
[
1539283140000,
6288.07
],
[
1539283440000,
6285.82
],
[
1539283740000,
6285.81
],
[
1539284041000,
6280.37
],
[
1539284340000,
6280.19
]
Please help me deal with this. And is there a possibility to decode the timestamp value to a date.
Correct json
{
"price": [
[
1539283140000,
6288.07
],
[
1539283440000,
6285.82
],
[
1539283740000,
6285.81
],
[
1539284041000,
6280.37
],
[
1539284340000,
6280.19
]
]
}
struct Root: Codable {
let price: [[Double]]
}
let res = try? JSONDecodable().decode(Root.self,from:jsonData)
I am trying to implement an array of dictionaries but I get an output different from my expectation.
In the following code snippet I create an array, a dictionary and execute the append operation:
var MemberArray = [[String: Any]]()
let dict = ["member_status":"1",
"member_id": memid ,
"membership_number": memshpid,
"name": memname,
"mobile":memno ,
"billing":"1"] as NSDictionary
MemberArray.append(dict as! [String : Any])
I need it to be this:
[
{
"member_status": 1,
"member_id": 3,
"membership_number": "GI99010286",
"name": "Thomas",
"mobile": "9873684678",
"billing": 0
},
{
"member_status": 1,
"member_id": 5,
"membership_number": "GI99010144",
"name": "Raj",
"mobile": "9873684678",
"billing": 1
}
]
But I get the following:
[
[
"member_status": 1,
"member_id": 3,
"membership_number": "GI99010286",
"name": "Thomas",
"mobile": "9873684678",
"billing": 0
],
[
"member_status": 1,
"member_id": 5,
"membership_number": "GI99010144",
"name": "Raj",
"mobile": "9873684678",
"billing": 1
]]
How can I achieve my goal?
For that you have to serialize that array. Here data is that array :
let dataSet = try! JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: dataSet, encoding: String.Encoding.utf8.rawValue)!
I want to access the array and get the text portion but it starts like this and I don't know how to get inside the array to get the text portion of it.
[
{
"textProns": [],
"sourceDictionary": "ahd-legacy",
"exampleUses": [],
"relatedWords": [],
"labels": [],
"citations": [],
"word": "car",
"partOfSpeech": "noun",
"attributionText": "from The American Heritage® Dictionary of the English Language, 4th Edition",
"sequence": "0",
"text": "An automobile.",
"score": 0
}]
This is what my code looks like
public static String parseJSONForDefinition(String jsonData) throws JSONException {
JSONArray array ;
return null;
}
Try this
with com.org.json package
String inputJson="[ { \"textProns\": [ ], \"sourceDictionary\": \"ahd-legacy\", \"exampleUses\": [ ], \"relatedWords\": [ ], \"labels\": [ ], \"citations\": [ ], \"word\": \"car\", \"partOfSpeech\": \"noun\", \"attributionText\": \"from The American Heritage® Dictionary of the English Language, 4th Edition\", \"sequence\": \"0\", \"text\": \"An automobile.\", \"score\": 0 } ]";
JSONArray arr=new JSONArray(inputJson);
System.out.println(((JSONObject)arr.get(0)).get("attributionText"));
With Jackson fasterxml api
String inputJson="[ { \"textProns\": [ ], \"sourceDictionary\": \"ahd-legacy\", \"exampleUses\": [ ], \"relatedWords\": [ ], \"labels\": [ ], \"citations\": [ ], \"word\": \"car\", \"partOfSpeech\": \"noun\", \"attributionText\": \"from The American Heritage® Dictionary of the English Language, 4th Edition\", \"sequence\": \"0\", \"text\": \"An automobile.\", \"score\": 0 } ]";
ObjectMapper mapper=new ObjectMapper();
ArrayNode arrayNode=(ArrayNode)mapper.readTree(inputJson);
System.out.println(arrayNode.get(0).path("attributionText"));