0

How to transform JSON structure to an new array using Swift?

Initial JSON

{
  "group1": {
    "1/30/21": 100,
    "1/31/21": 200
  },
  "group2": {
    "1/30/21": 200,
    "1/31/21": 300
  },
  "group3": {
    "1/30/21": 300,
    "1/31/21": 500
  }
}

The array I'd like to convert would be like:

[
  {
    "group1": 100,
    "group2": 200,
    "group3": 300,
    "date": "1/30/21",
  },
  {
    "group1": 200,
    "group2": 300,
    "group3": 500,
    "date": "1/31/21",
  }
]
2
  • And how dynamic is the data, could there be more groups or more dates per group? Have you tried anything yourself you can share? Commented Feb 6, 2021 at 16:28
  • Yes, it could be more groups and more dates per group but each size of object is same Commented Feb 6, 2021 at 16:37

1 Answer 1

2

First use JSONSerialization to convert the json to a dictionary

let dictionary = try JSONSerialization.jsonObject(with: jsonIn.data(using: .utf8)!) as! [String: [String: Int]]

Then in two steps convert to the expected format by first creating a dictionary where the date is the key and groups and numbers (as a tuples) are the values

var temp = [String: [(String, Int)]]()

dictionary.forEach { key, value in
    for (innerKey, innerValue) in value {
        temp[innerKey, default: []].append((key, innerValue))
    }
}

Then use this dictionary to create the array of dictionaries

let output = temp.map { (key, tuples) -> [String: Any] in
    var result = [String: Any]()
    for tuple in tuples {
        result[tuple.0] = tuple.1
    }
    result["date"] = key
    return result
}

and then back to json

let jsonOut = try JSONSerialization.data(withJSONObject: output)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.