【发布时间】:2012-10-31 19:59:51
【问题描述】:
我正在使用 YAML 文件,当我将其转换为哈希时,其中一个值是字符串。
这是我正在处理的文档:
---
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
这就是我处理文件的方式:
thing = YAML.load_file('login_as_user.yml')
http = thing['http_interactions']
alldoc = http[0]
response = alldoc['response']
body = response['body']
bodystring = body['string']
字符串是body 键的值,如果我在正文中打印它,它会返回给我:
puts 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"}
但是如果我像这样检查这个字符串的值:
puts bodystring
格式会很好:
{
"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"
}
}
所以问题出在转义符号中,当我打开文件并再次写入时,在处理数据后,格式错误。
如果有人可以帮助我,我将不胜感激。
【问题讨论】:
-
当您说您使用
body['string']检查字符串的值时,围绕它的代码是什么?你用的是p吗?puts?你是在 irb 还是 rails 控制台?您是使用<%=...%>还是使用<%=debug...%>在rails 视图中显示它?另外,能否把YAML.load_file读到的文件内容贴出来? -
我编辑了我的问题,所以现在更详细了。我现在使用 IRB。感谢您的帮助!
-
干得好——这是个好问题。