for an http get request's query string ?text=&index=10, how one can generate NSURLQueryItem for first key 'text' with empty value? Or does above kind of query string generation not supported by NSURLComponents ?
Actually earlier what I am trying to accomplish is creating a category on NSDictionary that will return array of NSURLQueryItems after parsing through its key-value pairs. For some keys like 'text', I am passing [NSNull null] as value and so unable to generate the needed NSURLQueryItems array. But then specifying #"" as value in the key for NSDictionary and also suggested by #Alladinian in the comment above the problem has been solved.
Related
I have a String based Key-Value Array inside of a String, and I want to decoded it and assign the value to an existing array in Swift 4.2. For example:
let array: [String:String] = []
let stringToDecode = “[\“Hello\”:\”World\”, \"Key\":\"Value\"]”
// I want ‘array’ to be assigned
// to the value that is inside
// ‘stringToDecode’
I’ve tried the JSON decoder, but it couldn’t decode it. Is there a simple way to do this? Thank you.
Try using a library like SwiftyJson, it makes working with json much easier.
Why does the second line give an error?
items = serializer.DeserializeObject(json)
value = items ["key"]
Error: Type 'object' does not support slicing. (BCE0048)
I tried various ways to indicate that "items" is a dictionary, to no avail.
Solution:
items as Dictionary [of string, object] = serializer.DeserializeObject(json)
I'm working on a configuration file parser and I need help parsing key: value pairs into a hash.
I have data in the form of: key: value key2: value2 another_key: another_value.
So far I have code in form of
line = line.strip!.split(':\s+')
which returns an array in the form of
["key:value"]["key2: value2"]["another_key: another_value"]
How can I turn these arrays into a single hash in the form of
{key=>value, key2=>value2, another_key=>another_value}
I'm not sure if the key:value pairs need to be in the form of a string or not. Whatever is easiest to work with.
Thanks for your help!
This is the solution I found:
line = line.strip.split(':')
hash = Hash[*line]
which results in the output{"key"=>"value"}, {"key2"=>"value2"}
Very very close to Cary's solution:
Hash[*line.delete(':').split]
Even simpler:
Hash[*line.gsub(':',' ').split]
# => {"key"=>"value", "key2"=>"value2", "another_key"=>"another_value"}
Assuming the key and value are single words, I'd probably do something like this:
Hash[line.scan(/(\w+):\s?(\w+)/)]
You can change the regex if it's not quite what you are looking for.
I’m trying to parse some JSON from the twitter API and extract the value of a key (“media_url”), which is a sub-key of the key (“entities”)
so far I have:
url = 'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&screen_name=print_broadcast&count=1'
response = RestClient.get(url)
data=response.body
result = JSON.parse(data)
How would I extract a key value from the parsed JSON?
I’ve tried
result[“entities”]
etc, but I get en error when trying to convert a string to integer... the result of my parsed JSON is an array - shouldn't this be a hash?
Sorry for the dumb questions.
Any help would be appreciated.
The JSON output is actually a list. Granted, it only has one element, but it's still a list.
First get result[0], then you can access ['entries'].
I'm having success when I use this code to get a string from an array of file names called "fileList":
cell.timeBeganLabel.text = [[[self.fileList objectAtIndex:[indexPath row]] lastPathComponent] stringByDeletingPathExtension];
so I expected the same code to generate the same string as a key for me in this:
NSDictionary *stats = [thisRecordingsStats objectForKey:[[[self.fileList objectAtIndex:[indexPath row]] lastPathComponent] stringByDeletingPathExtension]];
cell.durationLabel.text = [stats objectForKey:#"duration"];
or this:
NSDictionary *stats = [thisRecordingsStats objectForKey:#"%#",[[[self.fileList objectAtIndex:[indexPath row]] lastPathComponent] stringByDeletingPathExtension]];
Both build without error, and the log shows my data is there: but I'm getting a blank UILabel.
Have I not written the dynamic key generator correctly?
I'm having success when I use this code to get a string from an array of file names called "fileList":
cell.timeBeganLabel.text = [[[self.fileList objectAtIndex:[indexPath row]] lastPathComponent] stringByDeletingPathExtension];
So, the result of that message expression is your key, right?
That is to say, the keys in your dictionary are filenames without extensions?
so I expected the same code to generate the same string as a key for me in this:
NSDictionary *stats = [thisRecordingsStats objectForKey:[[[self.fileList objectAtIndex:[indexPath row]] lastPathComponent] stringByDeletingPathExtension]];
cell.durationLabel.text = [stats objectForKey:#"duration"];
You compute the filename without extension as before.
You look up the object for this string in the thisRecordingsStats dictionary, thus obtaining another dictionary, with which you initialize the stats variable.
You look up the object for the “duration” key in the stats dictionary, and set the durationLabel's text to this object.
or this:
NSDictionary *stats = [thisRecordingsStats objectForKey:#"%#",[[[self.fileList objectAtIndex:[indexPath row]] lastPathComponent] stringByDeletingPathExtension]];
Adding the #"%#", part doesn't make sense, since objectForKey: doesn't take a format string. Compare the documentation for NSString's stringWithFormat: method to the documentation for NSDictionary's objectForKey: method.
The code “works” because what you have passed as the argument to objectForKey: is a comma expression. C's comma operator evaluates both sides and evaluates to the right-hand side. However, in this case as in most others, it adds nothing. For reasons like this, the comma operator is rarely used and even more rarely used on purpose.
Cut the #"%#", part out.
Back to the problem:
Both build without error, and the log shows my data is there: but I'm getting a blank UILabel.
Well, you say the key you're generating from the string in your fileList array shows up in the UILabel, so the problem is one of these:
thisRecordingStats is nil.
thisRecordingStats does not contain an object for the key you generated from the string in self.fileList.
thisRecordingStats does contain an object for the key you generated from the string in self.fileList, and it is a dictionary, but it does not contain a value for the key “duration”.
thisRecordingStats does contain an object for the key you generated from the string in self.fileList, and it is a dictionary, and it contains a value for the key “duration”, but that value is an empty (zero-length) string.
You should also check the Debugger Console for messages that suggest other problems. For example, a “does not respond to selector” message may be because thisRecordingStats contains an object for the key you generated from the string in self.fileList, but it is not a dictionary.
Finally, I suggest constructing one or more model object classes instead of nesting dictionaries like this. It tends to make the code much easier to read and to debug. In particular, the dictionaries that ostensibly have objects for the key “duration” should be model objects.