我正在使用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"
}
}
所以问题在于转义符号,当我打开文件并再次写入文件时,在处理数据后,它的格式化错误。
如果有人能帮助我,我会很感激。
答案 0 :(得分:1)
正文只是一个字符串,但该字符串是哈希的JSON编码。要将该JSON编码转换为Ruby哈希,请使用json gem:
require 'json'
body_hash = JSON.parse(bodystring)
如果你在Rails中,你可能已经加载了json gem并且不需要require
。