0

There is a dictionary which is formatted as a JSONObject by the following code:

json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) 
as! NSDictionary

Data

{
"word": "detrimental",
"results": [
{
    "definition": "(sometimes followed by `to') causing harm or injury",
    "partOfSpeech": "adjective",
    "synonyms": [
        "damaging",
        "prejudicial",
        "prejudicious"
    ],
    "similarTo": [
        "harmful"
    ],
    "derivation": [
        "detriment"
    ]
}
],
"syllables": {
"count": 4,
"list": [
    "det",
    "ri",
    "men",
    "tal"
]
},
"pronunciation": {
"all": ",dɛtrə'mɛntəl"
},
"frequency": 2.77
}

I'm trying to output the data with a label

label.text = "\(json.valueForKeyPath("results.definition")!)"

But the output looks like this:

(
    "(sometimes followed by `to') causing harm or injury"
)

My question is what is the best way to make the output only show the text without "()"?

Is the only way that convert the json data to NSString and split it? I hope there is a better way if possible

Joey Zhang
  • 363
  • 6
  • 18
  • Possible duplicate of [Remove characters from NSString?](http://stackoverflow.com/questions/925780/remove-characters-from-nsstring) – Ozgur Vatansever May 22 '16 at 06:01

1 Answers1

2

Don't use string manipulation to remove the parentheses! Get the right string in the first place.

The problem is that results in your JSON contains an array of multiple results:

"results": [ ... ]

When valueForKeyPath encounters an array, it applies the rest of the key path (in your case, definition) to each item in the array, and returns another array with all of the results.

When you convert an array to a string you get ( ) surrounding the items in the array. (And quotes around strings, and commas between each item. You probably don't want those either.)

So if your JSON had more than one result, like this:

"results": [
            {
            "definition": "first definition",
            },
            {
            "definition": "second definition",
            }
            ],

the text in your label would be:

(
    "first definition",
    "second definition"
)

To fix this, extract only the single item in the results array that you actually want. You cannot do this with valueForKeyPath, unfortunately (see this answer). You are better off checking the structure of your JSON at each level, anyway, instead of assuming that you have been passed data in the exact format you expect.

if let json = (try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())) as? NSDictionary,
       results = json["results"] as? NSArray,
       firstResult = results.firstObject as? NSDictionary,
       definition = firstResult["definition"] as? String {
   label.text = definition
}
Community
  • 1
  • 1
Kurt Revis
  • 27,695
  • 5
  • 68
  • 74