1

我正在使用 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"
 }
}

所以问题出在转义符号中,当我打开文件并再次写入时,在处理数据后,它的格式错误。

如果有人可以帮助我,我将不胜感激。

4

1 回答 1

1

正文只是一个字符串,但该字符串是哈希的 JSON 编码。要将 JSON 编码转换为 Ruby 哈希,请使用json gem:

require 'json'
body_hash = JSON.parse(bodystring)

如果你在 Rails 中,你可能已经加载了 json gem,不需要require.

于 2012-11-12T12:53:18.587 回答