How to turn my JSON result into an array or object - json

I have been searching every where, but cannot get to the right answer. I receive a Json result with the following structure
{
result = {
"2ab5a003-0120-4c01-80f2-a237dcf4ba14" = {
icon = garden;
id = "2ab5a003-0120-4c01-80f2-a237dcf4ba14";
index = 1;
name = "Tafel hoek";
parent = "855113f1-f488-4223-b675-2f01270f573e";
};
"2afd6093-ca6d-4e52-aaca-336ab76ea454" = {
icon = default;
id = "2afd6093-ca6d-4e52-aaca-336ab76ea454";
index = 11;
name = Badkamer;
parent = "9919ee1e-ffbc-480b-bc4b-77fb047e9e68";
};
};
status = 200;
}
Because I don't know the 1st key in the result I am lost to get the separate items. Is there any one who can help me ? Thanks in advance
my code is:
{ print("Error: ")
print(error!)
} else { // no error
if let urlContent = data { // 3
do { // 4
let json = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(json)
} catch {
print("JSON processing failed")
} // end 4 do
} // end 3 let urlContent
} // end 2 if error}

Since you have the dictionary for key result, you can enumerate it as usual:
if let result = json["result"] as? [String:[String:Any]] {
for (key, value) in result {
let name = value["name"] as! String
let index = value["index"] as! Int
print (key, name, index)
}
}

Can you post your code ,i think that is not a valid json format and tell me where you are struggling to parse.ignore that key and try as usual

Related

How to Display data from JSON in Alphabetical Sections Swift?

I've been using JSONParsing to display my data when you search for a term. Now I want to list out all of those terms in an alphabetized list. But am having trouble getting the code to work correctly. I've replicated some code from someone else that was having the same problem and got that to work but I'm having trouble implementing my own code.
I currently am parsing my JSON with this code:
func parseJSONSignDictionary() {
if let url = Bundle.main.url(forResource: "csvjson", withExtension: "json") {
do {
let date = Date()
let data = try Data(contentsOf: url)
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
(json["results"] as? [[String:Any]])?.forEach { j in
if let name = j["identifier"] as? String, let id = j["id"] as? Int {
let sign = Signs(name: name, number: id)
signsArray.append(sign)
}
}
}
print("Took", Date().timeIntervalSince(date))
} catch {
print(error.localizedDescription)
}
}
}
Edit to add some more code, this is my Signs class, which would replace the Restaurant Array/Class:
class Signs: NSObject, Decodable, NSCoding {
private var _signName: String!
private var _signNumber: Int!
var signName: String {
return _signName
}
var signNumber: Int {
return _signNumber
}
func encode(with aCoder: NSCoder) {
aCoder.encode(signName, forKey: "signNameKey")
}
required init?(coder aDecoder: NSCoder) {
print("Trying to turn Data into Sign")
self._signName = aDecoder.decodeObject(forKey: "signNameKey") as? String
}
init(name: String, number: Int) {
self._signName = name
self._signNumber = number
}
}
The code from another StackOverflow that I'm trying to use is from here. question:Display data from JSON in alphabetical sections in Table View in Swift
func makeDataSource(names:[String:[AnyObject]]) {
var dict = [String:[Restaurant]]()
let letters = NSCharacterSet.letters
for (_,value) in names {
//Iterating Restaurants
for resObj in value {
if let restaurantName = resObj["name"] as? String {
let restaurant = Restaurant(name: restaurantName)
var key = String(describing: restaurant.name.first!)
//To check whether key is alphabet or not
key = isKeyCharacter(key: key, letters: letters) ? key : "#"
if let keyValue = dict[key] {
//Already value exists for that key
var filtered = keyValue
filtered.append(restaurant)
//Sorting of restaurant names alphabetically
//filtered = filtered.sorted(by: {$0.0.name < $0.1.name})
dict[key] = filtered
} else {
let filtered = [restaurant]
dict[key] = filtered
}
}
}
}
//To sort the key header values
self.dataArray = Array(dict).sorted(by: { $0.0 < $1.0 })
//Logic to just shift the # category to bottom
let temp = self.dataArray[0]
self.dataArray.removeFirst()
self.dataArray.append(temp)
self.indexTitles = Array(dict.keys.sorted(by: <))
let tempIndex = self.indexTitles[0]
self.indexTitles.removeFirst()
self.indexTitles.append(tempIndex)
}
I have my own array that would replace Restaurant, called Signs.
if let restaurantName = resObj["name"] as? String {
I'm also wondering where this "name" is being pulled from? Is it the array/model which has the var name?
I'm not sure since I have a way to access the JSON data with my own function if I even need to try to use the getdata() function.
I just wanna understand what I'm missing, and how to do it on my own to get the code to work properly.

Need help in JSON parsing

I am getting data from API and I need to filter the array of dictionary based upon "total_price" tag, now the condition is I want only those flights whose price is between "35.0" to "55.0"
{
airline = 9W;
"available_seats" = "<null>";
bags = (
);
currency = USD;
destination = 38551;
origin = 39232;
"price_details" = {
};
"rate_plan_code" = WIP;
routes = (
);
taxes = "17.51";
"total_price" = "31.7";
}
As the total_price tag is coming as string I am not sure how to filter it using predicate etc. I need to filter the json response itself, no models were created for this API response.
Since you want to filter on prices I assume you get an array and I have further assumed in my code this array is inside a dictionary with the key "flights" so you need to change this key to whatever you have
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
if let flights = json["flights"] as? [[String: Any]] {
let filtered = flights.filter {
if let str = $0["total_price"] as? String, let price = Double(str) {
return price >= 35.0 && price <= 55.0
}
return false
}
print(filtered.count) // replace with more meaningful code :)
}
}
} catch {
print("Decode failed: \(error)")
}

Trouble getting data from TheMovieDB API with Swift JSON

I am brand new to using JSON and wanted to get started with a simple app to provide a movie overview when you type in a title. My below code returns everything in one big string. How do I get just one piece of information like the overview or year?
With my below attempt, print(obj["overview"] as Any)) prints "nil" and print(obj) looks like this:
{
page = 1;
results = (
{
adult = 0;
"backdrop_path" = "/A0aGxrCGRBuCrDltGYiKGeAUect.jpg";
"genre_ids" = (
53,
80
);
id = 680;
"original_language" = en;
"original_title" = "Pulp Fiction";
overview = "A burger-loving hit man, his philosophical partner, a drug-addled gangster's moll and a washed-up boxer converge in this sprawling, comedic crime caper. Their adventures unfurl in three stories that ingeniously trip back and forth in time.";
Current Code:
let query = "Pulp+Fiction"
let urlString = "https://api.themoviedb.org/3/search/movie?api_key={MYAPIKEY}&query=\(query)"
let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error as Any)
} else {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!) as Any
if let obj = parsedData as? NSDictionary {
print(obj["overview"] as Any)
print(obj)
}
} catch {
print("error")
} }
}.resume()
}
// write this extension anywhere in your any swift file
extension String{
func toDictionary() -> NSDictionary {
let blankDict : NSDictionary = [:]
if let data = self.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
} catch {
print(error.localizedDescription)
}
}
return blankDict
}
}
//now in your code modify as
if data != nil {
let responseString = String(data: data!, encoding: .utf8)!
if(responseString != "")
{
//convert response string into dictionary using extended method
let responseValues = responseString.toDictionary()
//access value using keyPath using
let value = responseValues.value(forKeyPath: "key.key2")
//where key2 is the target key which is inside the value of key
}
}
First of all JSON results are never Any. As already mentioned in the comments the root object is a dictionary
if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
The key overview is in array for key results
let results = parsedData["results"] as? [[String:Any]] {
You have to iterate over the array to get the values for key overview
for result in results {
print(result["overview"] as? String ?? "no value for key overview")
}
}
It's highly recommended to use the Codable protocol and custom structs in Swift 4.

Swift Facebook Get Friends Graph Request Error

So, I am trying to get a list of all other facebook friends also connected on my app.
After doing an FBSDKgraphrequest, I get the right data (see below) and then convert it to an NSDictionary. The data looks like this:
{
friends = {
data = (
{
id = 10154257515635281;
name = "Hector Judd";
},
{
id = 151132798649181;
name = "Arch Tester Dev";
}
);
paging = {
cursors = {
after = QVFIUndVRFZAINXhCSlAzdnNGeUUwTHdhamNpc3NFbjR2NjF4dk40N3ZAZAR2lNLXM0Q3BxLW90REVsaFk3aU13Um1Ca0NOd0ZAXN2gxaDF2emhYem9BMjhkMVl3;
before = QVFIUlo2a1Q4UGhpWmY2SFNWbUtpMVcxZAnEtR01KSlUyeVEtMU9GbjNkRHp2bTFKY0VoVm5xX3dNLXEwMG5OY0Q0My0ZD;
};
};
summary = {
"total_count" = 831;
};
};
id = 10208811056967519;
}
I then try and unpack it with multiple if let statements, but end up getting the error: Segmentation fault 11. See code below.
func getFriends() {
let parameters = ["fields": "friends"]
FBSDKGraphRequest(graphPath: "me", parameters: parameters).startWithCompletionHandler({ (connection, result, error) -> Void in
if error != nil {
print(error)
} else {
if let result = result as? NSDictionary {
if let data = result["friends"] as? NSDictionary {
if let friendData = data["data"] as? NSArray {
for friend in friendData {
friendIds.append(friend["id"] as String)
print(friendIds)
}
}
}
}
}
})
}
I am relatively new to programming and am struggling to work out a good way to do this. Any suggestions would be much appreciated!! Thanks.
Try to declare your friendData variable as a NSDictionary in your Loop
for friend in friends {
if let friendData = friend as? NSDictionary {
friendIds.append(friendData["id"] as! String)
}
}

Optional String added to output - Swift

Been working on pulling data from an API, finally got that to work (I believe correctly) but when I print out variables within the dictionary, "Optional" gets added to the string
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary
print(jsonResult)
if (jsonResult != nil) {
if let players = jsonResult?["players"] as? [Dictionary<String, AnyObject>] {
for player in players {
let personID = player["name"]
print(personID)
}
}
} else {
print("No Data")
// couldn't load JSON, look at error
}
}
Sample of the JSON Output:(note I cut this down and used only the first element)
Optional({
players = (
{
name = "Derek Anderson";
},
Print statement:
Optional(Derek Anderson)
My assumption here is that its printing the Optional Dictionary and then grabbing the "players" name. Meaning I haven't pulled just that name out. I've pulled the name out of the players array, not the Optional.
I feel like I may be adding that Optional Array in some way though, cant seem to figure this one out!
Solved, the variable needs to be unwrapped:
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary
print(jsonResult)
if (jsonResult != nil) {
if let players = jsonResult?["players"] as? [Dictionary<String, AnyObject>] {
for player in players {
let personID = player["name"]!
print(personID)
}
}
} else {
print("No Data")
// couldn't load JSON, look at error
}
}