JSON 在通过 Ruby 中的 TCP 发送后不再可解析 [英] JSON no longer parsable after being sent through TCP in Ruby

查看:24
本文介绍了JSON 在通过 Ruby 中的 TCP 发送后不再可解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个传递字符串的基本客户端和服务器,我已将其更改为 JSON.但是 JSON 字符串只能在通过 TCP 发送之前进行解析.发送后,字符串版本是相同的(在 chomp 之后),但在服务器端,它不再正确处理 JSON.这是我的一些代码(修剪了其他位)

I've created a basic client and server that pass a string, which I've changed to JSON instead. But the JSON string is only parsable before it gets sent through TCP. After it's sent, the string version is identical (after a chomp), but on the server side it no longer processes the JSON correctly. Here is some of my code (with other bits trimmed)

部分客户端代码

require 'json'
require 'socket'

foo = {'a' => 1, 'b' => 2, 'c' => 3}

puts foo.to_s + "......."

foo.to_json
puts foo['b'] # => outputs the correct '2' answer

client = TCPSocket.open('localhost', 2000)
client.puts json
client.close;

部分服务器代码

require 'socket'
require 'json'
server = TCPServer.open(2000)

while true

  client = server.accept # Accept client
  response = client.gets

  print response
  response = response.chomp
  response.to_json

  puts response['b'] # => outputs 'b'

end

输出 'b' 应该是 '2'.我该如何解决这个问题?

The output 'b' should be '2' instead. How do I fix this?

谢谢

推荐答案

您在服务器中编写了 response.to_json.这会将字符串转换为 JSON,然后将其丢弃.而且我也不喜欢 .chomp.

In your server you wrote response.to_json. This turns a string to JSON, then throws it away. And I don't like the .chomp, either.

试试

response = client.gets
hash = JSON.parse(response)

现在 hash 是一个 Ruby Hash 对象,其中包含您的数据,hash['b'] 应该可以正常工作.

Now hash is a Ruby Hash object with your data in it, and hash['b'] should work correctly.

这篇关于JSON 在通过 Ruby 中的 TCP 发送后不再可解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆