将 Ruby 字符串编码为 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6783988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:56:13  来源:igfitidea点击:

Encode a Ruby string to a JSON string

rubystringjsonescaping

提问by Félix Saparelli

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

json宝石不允许直接编码字符串到他们的JSON表示。我暂时移植了这段 PHP 代码:

$text = json_encode($string);

to this Ruby:

到这个红宝石:

text = string.inspect

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

它似乎完成了这项工作,但由于某种原因,如果它string本身包含一个带有换行符的文字字符串(它实际上是 JS 代码),这些换行符\n将保持原样\n,而不是被编码为\\n. 我可以理解这是否是 的正确行为#inspect,但是...

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

如何在 Ruby 中将字符串值编码为其 JSON 表示?

采纳答案by Thai

As of Ruby 2.1, you can

从 Ruby 2.1 开始,您可以

require 'json'

'hello'.to_json

回答by John

This works with the stock 1.9.3+ standard library JSON:

这适用于 1.9.3+ 标准库 JSON:

require 'json'
JSON.generate('foo', quirks_mode: true) # => "\"foo\""

Without quirks_mode: true, you get the ridiculous "JSON::GeneratorError: only generation of JSON objects or arrays allowed".

没有quirks_mode: true,您会得到可笑的“JSON::GeneratorError: only generation of JSON objects or arrays allowed”。

回答by Cody Caughlan

There are a myriad of JSON gems for Ruby, some pure Ruby some C-based for better performance.

Ruby 有无数的 JSON gem,一些是纯 Ruby,一些是基于 C 的,以获得更好的性能。

Here is one that offers both pure-Ruby and C: http://flori.github.com/json/

这是一个同时提供纯 Ruby 和 C 的:http: //flori.github.com/json/

And then its essentially:

然后它本质上是:

require 'json'
JSON.encode(something)

A popular JSON encoder/decoder with native C-bindings for performance is Yajl: https://github.com/brianmario/yajl-ruby

Yajl 是一种流行的具有本地 C 绑定以提高性能的 JSON 编码器/解码器:https: //github.com/brianmario/yajl-ruby

UPD from @Stewart: JSON.encodeis provided by rails as is object.to_json. For uses outside of rails use JSON.generatewhich is in ruby 1.9.3 std-lib. – Stewart

来自@Stewart 的 UPDJSON.encode由 rails 按原样提供object.to_json。对于 Rails 之外的用途JSON.generate,请使用ruby 1.9.3 std-lib。– 斯图尔特