Swift: escape characters appear in json string - ios

I'm constructing a JSON string by concatenating strings. To get the quotes correct for the web service (no quotes around numbers), I'm using escape characters. When I print the resulting string in Xcode, it looks fine.
{"number":999,"name":"new"}
But when I use Wireshark to capture what's going over the wire, I can see the escape characters in the string.
"{\"number\":999,\"name\":\"new\"}"
Here's the code that creates the string:
let jsonString:String = "{\"number\":" + num + ",\"name\":\"" + name + "\"}"
How can I create the string so the escape characters aren't there?
Thanks

The reason I couldn't send the JSON as a dictionary is that Swift dictionaries are unordered. In this case, the server is using MongoDB. I fixed the issue server side instead of trying to hack around it in the client.
Here's the reason: "Why does it happen: MongoDB uses a binary data format called BSON. In BSON, the order of keys always matters. Notice, in JSON an object is an unordered set of key/value pairs."
http://devblog.me/wtf-mongo

I'm fairly certain that the escape characters are being inserted by Wireshark in it's own output.

Related

NSSet full of NSStrings. When I print the set to the console, the results are unexpected

Here's what happens:
Internal database stuff: one class has a string property on it, that stores a phone number. This number is set using the code
CFBridgingRelease(ABMultiValueCopyValueAtIndex(ABRecordCopyValue(record, kABPersonPhoneProperty), 0));
My function: finds all objects of this type, and stores phone numbers of each object in an NSMutableSet.
Debug: I print the description of the set to the console.
Results:
Some of the set's objects look as expected (the majority actually): "+64 27 0124 975"
Some are missing quotation marks: 027 7824 565
Some have weird unicode symbols: "021\U00a0026\U00a017788"
My question:
Why the difference - what does it mean, and do I need to fix anything?
NSLog with %# – as I assume you are using – has some intelligence in how it presents NSStrings as it calls the description method. If the string has anything other than alphanumerics, such as the '+' or '\' above, it will use quotes. The string with unicode characters simply has its characters encoded as shown, and they are automatically converted into this lossless format. You should be able to convert it to something prettier for the console if you really need to with something like this:
NSLog(#"%#", [NSString stringWithCString:[myString.description cStringUsingEncoding:NSASCIIStringEncoding] encoding:NSNonLossyASCIIStringEncoding]);

URL Escape in Uppercase

I have a requirement to escape a string with url information but also some special characters such as '<'.
Using cl_http_utility=>escape_url this translates to '%3c'. However due to our backend webserver, it is unable to recognize this as special character and takes the value literally. What it does recognize as special character is '%3C' (C is upper case). Also if one checks http://www.w3schools.com/tags/ref_urlencode.asp it shows the value with all caps as the proper encoding.
I guess my question is is there an alternative to cl_http_utility=>escape_url that does essentially the same thing except outputs the value in upper case?
Thanks.
Use the string function.
l_escaped = escape( val = l_unescaped
format = cl_abap_format=>e_url ).
Other possible formats are e_url_full, e_uri, e_uri_full, and a bunch of xml/json stuff too. The string function escape is documented pretty well, demo programs and all.

How to make Rails 3 JSON parse doubly quoted strings and single number

Background
On the json.org website, a string is defined as "char+" where char+ is one or more char. A char is any unicode character except " or \. A subset of control characters are allowed, just escape them:
"foo" "2" "\\"
In Javascript, if you want to parse a string, it needs to be enclosed:
"\"foo\"" or '"foo"', but not "'foo'"
In Rails 3, the JSON gem that runs C or pure Ruby code is default.
As per the accepted answer, the gem parses JSON documents rather than elements. A document is either a collection in the form of key, value (object/hash) or values (array).
The problem
Strings
Let's say we want to parse the string foo, We would need to enclose it as "\"foo\"" or '"foo"'
JSON.parse("\"foo\"")
JSON.parse('"foo"')
yield
JSON::ParserError unexpected token at '"foo"'
meaning it can't parse "foo"
Numbers
The same goes for numbers: '3' or "3" will yield Needs at least two octets.
Larger numbers ( an octet is a byte, so two utf8 characters are two bytes ): '42' or "42" simply yield the same JSON::ParserError unexpected token at '42'
The workaround
The gem correctly parses these things if they are in an array: '["foo"]' or '[3]'
jsonstring = '"foo"'
JSON.parse( "[#{jsonstring}]" )[0]
yields
"foo"
This is ridiculous. Am I not understanding something correctly? Or is this gem bugged?
json.org states:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Since "foo" is neither of the above you are getting the error message. To further concrete it have a look at Ruby JSON Parser, the documenation states:
To create a valid JSON document you have to make sure, that the output is embedded in either a JSON array [] or a JSON object {}. The easiest way to do this, is by putting your values in a Ruby Array or Hash instance.
Hence what you are mentioning as "workaround" is actually the correct way to parse a string using the JSON parser.
Additional Info:
Parsing "\"foo\"" on jsonlint.com and json.parser.online.fr raises an error,
parsing ["foo"] passes the validation test on both the sites.

Request.Params understands [+] for a space

I'm doing a request...something like this:
#Request.Params["id"].ToString()
the value of id is encripted and returns something like
ZK10ez/BJARTw GVLbIeUOp
instead of
ZK10ez/BJARTw+GVLbIeUOp <- this is what is passed in the URL
In other words, it's replacing my plus sign [+] with spaces [ ].
I could just do a replace, but I don't know if this will happen in the future with other letters.
Anyone with the same problem?
A + character in a URL represents a space character. This is an aspect of URL encoding.
Make sure that you properly URL encode any data before using it in a URL. You should not try and replicate URL encoding / decoding by doing your own string replacements.
You can use Url.Encode to encode your data prior to using it in a query string.

Escape links in json using ruby

I have a JSON object and I want to convert it escaping / characters.
Object:
{
"id":"123",
"name":"test",
"link":"https://google.com"
}
Desired result:
{
"id":"123",
"name":"test",
"link":"https:\/\/google.com"
}
How can I do this transformation in Ruby, RoR?
If it is at all possible, modify the values before they are JSON'd. In activerecord, I believe you can change the value and convert it to JSON - so long as you don't save the model, that change will be discarded.
In ruby, JSON is just a string, so you could do
my_json.gsub('/', '\\/')
This would convert any forward slashes in the keys, too. I don't know of any reason a JSON string would contain forward slashes outside of a string, so that should be fine.
If you want to avoid converting the keys, you could use a (slightly complicated) regular expression:
my_json.gsub(/:\s*"[^"]*\/[^"]*"/) { |m| m.gsub('/', '\\/') }
This finds a section that starts with a colon, possibly some whitespace after that, then some double quotes. It then looks for some optional stuff (anything that isn't a double quote), then a forward slash, them more stuff that isn't a double quote, then an actual double quote. So essentially, the minimum it will find is :"/" - it then passes each matching string into the block, and runs the previous gsub to convert the slashes. The output of the block then replaces whatever was found in the initial gsub.
I'm sure there are neater ways, so play around.

Resources