iosjsonparsingswift4.2xcode11.3

Convert localizable.string file to JSON in iOS swift


I have 3 Localizable files in my project Localizable.string(English), Localizable.string(German) and Localizable.string(French) with several keys and values of form localizationKey1 = "Text1 in english"; . I want them to be converted in a single json file in format

{
    "localizationKey1": {
        "en": "Text1 in english",
        "de": "Text1 in german",
        "fr": "Text1 in french"
    },
    "localizationKey2": {
        "en": "Text2 in english",
        "de": "Text2 in german",
        "fr": "Text2 in french"
    } and so on depending on number of keys
}

How do I go about it?

EDIT: I was able to the required JSON format based on the answer by @Francis but the orders of the outer and inner keys are messed up. Is there any way to order them?


Solution

  • Try this

            let path1 = (Bundle.main.path(forResource: "Localizable", ofType: "strings", inDirectory: nil, forLocalization: "en"))
            let path2 = (Bundle.main.path(forResource: "Localizable", ofType: "strings", inDirectory: nil, forLocalization: "de"))
            let path3 = (Bundle.main.path(forResource: "Localizable", ofType: "strings", inDirectory: nil, forLocalization: "fr"))
            let dict1 = NSDictionary(contentsOfFile: path1!)
            let dict2 = NSDictionary(contentsOfFile: path2!)
            let dict3 = NSDictionary(contentsOfFile: path3!)
            var newDict = [String : Any]()
            for (key, value) in dict1! {
                var value2 = ""
                var value3 = ""
                if let keyVal = dict2?[key] as? String {
                    value2 = keyVal
                }
    
                if let keyVal = dict3?[key] as? String {
                    value3 = keyVal
                }
                let tempDict = ["en": value, "de": value2, "fr": value3]
                newDict["\(key)"] = tempDict
            }
            do {
              let data = try JSONSerialization.data(withJSONObject: newDict, options: .prettyPrinted)
              let dataString = String(data: data, encoding: .utf8)!
              print(dataString) //This will give you the required JSON format
            } catch {
              print("JSON serialization failed: ", error)
            }