将Ruby字符串编码为JSON字符串 [英] Encode a Ruby string to a JSON string

查看:170
本文介绍了将Ruby字符串编码为JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

json gem不允许直接将字符串编码为JSON表示形式。我暂时移植了这个PHP代码:

The json gem does not allow for directly encoding strings to their JSON representation. I tentatively ported this PHP code:

$text = json_encode($string);

到这个Ruby:

text = string.inspect

它似乎是做这份工作,但是某些原因,如果字符串本身包含带有换行符的文字字符串(实际上是JS代码),这些换行符 \\\
将保持原样 \\\
,不要编码为 \\\\
。我可以理解这是否是 #inspect 的正确行为,但... ...

and it seemed to do the job but for some reason if the string itself contains a literal string (it's actually JS code) with newlines, these newlines \n will stay as-is \n, not be encoded to \\n. I can understand if this is the correct behaviour of #inspect, but...

字符串值在Ruby中的JSON表示?

How does one encode a string value to its JSON representation in Ruby?

推荐答案

从Ruby 2.1开始,您可以

As of Ruby 2.1, you can

require 'json'

'hello'.to_json

这篇关于将Ruby字符串编码为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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