我正在使用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
键的值,如果我打印在体内,它会返回我:
身体:
{"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还是在轨道控制台?您是使用“<%=...%>”还是使用“<%=debug...%>”在轨道视图中显示它?另外,你可以发布由'YAML.load_file'读取的文件内容吗? –
我编辑我的问题,所以它现在更详细。我现在使用IRB。 谢谢你的帮助! –
干得好 - 现在这是个好问题。 –