I’m working with a YAML file, and when I convert it to a hash, one of the values is a string.
This is the document I’m working with:
---
http_interactions:
- request:
method: post
uri: http://********/client/api
body:
encoding: US-ASCII
string: *******************
headers: {}
response:
status:
code: 200
message: OK
headers:
Date:
- Mon, 24 Sep 2012 10:38:01 GMT
Set-Cookie:
- ***************; Path=/client
Content-Type:
- text/javascript;charset=UTF-8
Content-Length:
- "425"
body:
encoding: ASCII-8BIT
string: >
{
"loginresponse": {
"timeout": "43200",
"lastname": "frgrg",
"registered": "false",
"username": "rfrfr",
"timezone": "America\/New_York",
"firstname": "Mrfrfronika ",
"domainid": "3434444444444444444",
"type": "0",
"userid": "4444444444444444444444444444444441",
"sessionkey": "ewrffffffffffffffffffffff",
"timezoneoffset": "-4.0",
"account": "dddd"
}
}
http_version:
recorded_at: Mon, 24 Sep 2012 10:38:01 GMT
recorded_with: VCR 2.2.5
This is how I work with the file:
thing = YAML.load_file('login_as_user.yml')
http = thing['http_interactions']
alldoc = http[0]
response = alldoc['response']
body = response['body']
bodystring = body['string']
The string is the value of the body key, and if I print it in the body, it will return me this:
puts body
Body:
{"encoding"=>"ASCII-8BIT", "string"=>"{\n \"loginresponse\": {\n \"timeout\": \"43200\",\n \"lastname\": \"sdsd\",\n \"registered\": \"false\",\n \"username\": \"sdsdsd\",\n \"timezone\": \"America\\/New_York\",\n \"firstname\": \"sdasdas \",\n \"domainid\": \"ssssssssssss\",\n \"type\": \"0\",\n \"userid\": \"ssssssssssss1\",\n \"sessionkey\": \"sssssssssss",\n \"timezoneoffset\": \"-4.0\",\n \"account\": \"sadsadsa\"\n }\n}\n"}
But if I check the value of this string like this:
puts bodystring
It will be well formated:
{
"loginresponse": {
"timeout": "43200",
"lastname": "wwd",
"registered": "false",
"username": "dddd",
"timezone": "America\/New_York",
"firstname": "dddd ",
"domainid": "dddfdfdf",
"type": "0",
"userid": "dfsdfdsf",
"sessionkey": "dsfdsfdsf",
"timezoneoffset": "-4.0",
"account": "dsfdsfdsfd"
}
}
So the problem is in escaped symbols, and when I open the file and write it again, after working with the data, it has wrong formating.
I’d appreciate if somebody could help me.
The body is just a string, but that string is the JSON encoding of a hash. To turn that JSON encoding into a Ruby hash, use the json gem:
If you are in Rails, you’ve probably already got the json gem loaded and won’t need the
require.