How to get this subJson using SwiftyJSON? - json

"groups" : {
"232" : {
"name" : "John",
"age" : "22"
}
},
"143" : {
"name" : "Dylan",
"age" : "22"
}
}
How to get "name" using swiftyJSON? I got the id value but ["name"]'s always nil with this code:
for (results,subJson):(String, JSON) in json["groups"] {
let id = results
print(id) //--> 232
let name = subJson["\(id)"]["name"].string
print(name) //--> nil
}

The name key is inside subJson, remove the id subscript:
for (id, subJson):(String, JSON) in json["groups"] {
print(id)
if let name = subJson["name"].string {
print(name)
}
}

Related

Splitting Json to multiple jsons in NIFI

I have the below json file which I want to split in NIFI
Input:
[ {
"id" : 123,
"ticket_id" : 345,
"events" : [ {
"id" : 3322,
"type" : "xyz"
}, {
"id" : 6675,
"type" : "abc",
"value" : "sample value",
"field_name" : "subject"
}, {
"id" : 9988,
"type" : "abc",
"value" : [ "text_file", "json_file" ],
"field_name" : "tags"
}]
}]
and my output should be 3 different jsons like below:
{
"id" : 123,
"ticket_id" : 345,
"events.id" :3322,
"events.type":xyz
}
{
"id" : 123,
"ticket_id" : 345,
"events.id" :6675,
"events.type":"abc",
"events.value": "sample value"
"events.field_name":"subject"
}
{
"id" : 123,
"ticket_id" : 345,
"events.id" :9988,
"events.type":"abc",
"events.value": "[ "text_file", "json_file" ]"
"events.field_name":"tags"
}
I want to know can we do it using splitjson? I mean can splitjson split the json based on the array of json objects present inside the json?
Please let me know if there is a way to achieve this.
If you want 3 different flow files, each containing one JSON object from the array, you should be able to do it with SplitJson using a JSONPath of $ and/or $.*
Using reduce function:
function split(json) {
return json.reduce((acc, item) => {
const events = item.events.map((evt) => {
const obj = {id: item.id, ticket_id: item.ticket_id};
for (const k in evt) {
obj[`events.${k}`] = evt[k];
}
return obj;
});
return [...acc, ...events];
}, []);
}
const input = [{"id":123,"ticket_id":345,"events":[{"id":3322,"type":"xyz"},{"id":6675,"type":"abc","value":"sample value","field_name":"subject"},{"id":9988,"type":"abc","value":["text_file","json_file"],"field_name":"tags"}]}];
const res = split(input);
console.log(res);

Having trouble decoding retrieved JSON object in Swift

I am able to retrieve some JSON from an endpoint but then when I try to decode that JSON into my model object something goes wrong to where the json can't be parsed. I've made sure the properties in my model object matched the json keys, so I dont understand what the issue is. It prints out the catch block every time.
Here is my code to retrieve the json:
func getServiceProviders() {
let session = URLSession.shared
let url = URL(string: "http://exampleendpoint.com/example")!
URLSession.shared.dataTask(with: url) { data, response, error in
//Here is where I try to decode the json into my model object
do {
let jsonContent = try JSONDecoder().decode(ServiceObject.self, from: data!)
print(jsonContent)
} catch {
print("Ooops")
}
}.resume()
Here is my model object:
struct ServiceObject: Decodable {
let serviceproviders: [ServiceProvider]
struct ServiceProvider: Decodable {
let city: String
let coordinates: Location
let name: String
let overallGrade: String
let postalCode: Int
let state: String
let reviewCount: Int
}
struct Location: Decodable {
let latitude: Double
let longitude: Double
}
}
Here is what the json object I retrieve looks like:
{
"serviceproviders": [
{
"city" : "Beech Grove",
"coordinates" : {
"latitude" : "39.715417",
"longitude" : "-86.095646"
},
"name" : "William J Ciriello Plumbing Co Inc",
"overallGrade" : "A",
"postalCode" : "46107",
"state" : "Indiana",
"reviewCount" : 309
},
{
"city" : "Indianapolis",
"coordinates" : {
"latitude" : "39.922607",
"longitude" : "-86.0267094"
},
"name" : "Roby's Plumbing & Appliance Service",
"overallGrade" : "B",
"postalCode" : "46256",
"state" : "Indiana",
"reviewCount" : 903
},

How to convert JSON into associative/indexed array

Given this JSON
{
"users": [
{
"name" : "Elliot",
"type" : "Reader",
"age" : 23,
"social" : {
"facebook" : "https://facebook.com",
"twitter" : "https://twitter.com"
}
},
{
"name" : "Fraser",
"type" : "Author",
"age" : 17,
"social" : {
"facebook" : "https://facebook.com",
"twitter" : "https://twitter.com"
}
}
]
}
I need a function/library to return a map in order to do myMap[0].name to get the value "Elliot".
Is there anyone who can help me? Thanks.
I wish to access to that field in much beautiful notation associative-array like Res["users"][0].Name, or something like that.
As mentioned in comments, arguably the nicest way would be using structs
type User struct {
Name string `json:"name"`
Type string `json:"type"`
Age int `json:"age"`
Social struct {
Facebook string `json:"facebook"`
Twitter string `json:"twitter"`
} `json:"social"`
}
type Config struct {
Users []User `json:"users"`
}
rawJSON := []byte(`{...your config JSON in here...}`)
config := Config{}
if err := json.Unmarshal(rawJSON, &config); err != nil {
log.Fatal(err)
}
user := config.Users[0]
fmt.Printf(
"name: %s, type: %s, age: %d, facebook: %s, twitter: %s\n",
user.Name,
user.Type,
user.Age,
user.Social.Facebook,
user.Social.Twitter,
)
Result:
name: Elliot, type: Reader, age: 23, facebook: https://facebook.com, twitter: https://twitter.com
Go Playground

appending optional elements to an array from json in Swift

I have just started getting familiar with JSON. I have a class object that I am initialising by passing in a JSON. This object has an array that may be empty and I need to check it for value. so far I am trying:
init(json: JSON) {
id = json["id"].string
type = json["type"].string
text = json["text"].string
answer = json["answer"].string
format = json["format"].string
answeredBy = []
if let answeredByjson = json["answeredBy"].array {
for (_, userDict) in answeredByjson {
if let userDict = userDict as? [String : Any] {
answeredBy.append(JSON(User(dictionary: userDict)))
}
}
}
}
the elements in the array are dictionaries that have to be used to initialize another object (User).
the error I am getting is:
Expression type '[JSON]' is ambiguous without more context.
How can I update my code?
this is my json:
{
"answer" : "rachel",
"answeredBy" : {
"j1K4WXbOFRXfm3srk9oMtZJ8Iop2" : {
"email" : "an email",
"pictureURL" : "a URL",
"uid" : "j1K4WXbOFRXfm3srk9oMtZJ8Iop2",
"name" : "a name"
},
"vtYlmyerugedizHyOW6TV847Be23" : {
"email" : "an email",
"pictureURL" : "a URL",
"uid" : "vtYlmyerugedizHyOW6TV847Be23",
"name" : "Rusty Shakleford"
}
},
"format" : "field",
"id" : "1",
"type" : "text",
"text" : "In a foot race, Jerry was neither first nor last. Janet beat Jerry, Jerry beat Pat. Charlie was neither first nor last. Charlie beat Rachel. Pat beat Charlie. Who came in last?"
}
if let answeredByjson = json["answeredBy"].array {
...
}
produces an array [JSON], but you expect it to produce a dictionary [String: JSON]. That is why you receive:
Expression type '[JSON]' is ambiguous without more context
To produce a dictionary:
if let answeredByjson = json["answeredBy"].dictionary {
...
}
It you don't expect it to produce a dictionary [String: JSON] then this line doesn't make sense
for (_, userDict) in answeredByjson {

swift - JSON dictionary parsing

I have a JSON file like below, I want to parse it and populate my tableview.
What I want to get is "material", "categories", "product_types"
["facets": {
"material" : {
"data" : [
{
"count" : 3,
"value" : "95% Polyester, 5% Spandex"
},
{
"count" : 1,
"value" : "%100 Modal"
}
],
},
"categories" : {
"data" : [
{
"id" : "7",
"name" : "test"
}
],
},
"product_types" : {
"data" : [
{
"count" : 3,
"value" : "Sweatshirt"
},
{
"count" : 1,
"value" : "Babet"
},
],
}
}]
My code is:
var list: [String:JSON]? = [:]
func loadList(){
ModafiliAPI.sharedInstance.refine(callback: { (refineList) in
if let data = refineList["facets"].dictionaryValue as [String:JSON]?{
self.list = data
self.RefineTableView!.reloadData()
print(self.refineList!)
}
})
}
I observe that I can access "facets" from the print output. But in cellforrowat
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RefineCell") as! RefineTableViewCell
cell.refineList = self.refineList?[indexPath.row] //-->>error
return cell
}
I am getting the following error: Ambiguous reference to member 'subscript'
UITableViewCell:
var refineList:[String:JSON]?{
didSet{
self.setupRefineList()
}
}
Xcode doesn't know what type is refineList, it's ambiguous for him
try
cell.refineList = self.refineList?[indexPath.row] as! [String:JSON]
You may also check what cell.refineList type ?
Also try:
guard let list = refineList?[indexPath.row] else {
print ("Unexpected error !!")
return cell
}
cell.refineList:[String:JSON] = list as! [String:JSON]