当前位置: 首页 > news >正文

JSON dump in Ruby

 

In Ruby, the json library’s API differs from Python’s json.dump.

The equivalent in Ruby would be something like this:

require 'json'data = {name: "Christopher",message: "こんにちは世界"  # Japanese characters to test non-ASCII
}# Pretty-print with indentation and allow non-ASCII characters
json_str = JSON.pretty_generate(data, indent: '  ', ascii_only: false)puts json_str

 

Explanation:

  • JSON.pretty_generate(obj, opts = {}) → gives indentation and line breaks.

  • indent: ' ' → sets 2-space indentation.

  • ascii_only: false → prevents escaping non-ASCII characters (i.e., keeps UTF-8 characters intact).

  • Ruby doesn’t have ensure_ascii like Python, but ascii_only: false is the direct counterpart.

If instead you want to dump directly to a file (like Python’s json.dump does):

File.open("output.json", "w:utf-8") do |f|f.write(JSON.pretty_generate(data, indent: '  ', ascii_only: false))
end

 


Would you like me to also show you the non-pretty (compact but still UTF-8 safe) equivalent of Python’s json.dump(..., ensure_ascii=False) without indentation?

 

http://www.jsqmd.com/news/5070/

相关文章:

  • 详细介绍:python+django/flask+uniapp基于微信小程序的瑜伽体验课预约系统
  • smartctl on FreeBSD: Please specify device type with the -d option.
  • GraphRAG对自然语言处理中深层语义分析的革命性影响与未来启示 - 教程
  • prefect
  • 生成算数问题*30
  • 6379:统计学生信息(使用动态链表完成)
  • 详细介绍:云原生 vs 传统部署
  • 使用IOT-Tree Server通过FINS协议连接欧姆龙CP2E-N系列PLC - 详解
  • 实用指南:疑难bug之正确处理InterruptedException
  • 课后作业1-3
  • GNSS精度判断和协方差矩阵 - MKT
  • 实用指南:clsx:高效处理 React 条件类名的实用工具
  • Insightly模板页面存储型XSS漏洞分析与复现
  • 记录 | 关于陪伴型交互AI的一些探讨
  • luogu P1719 最大加权矩形
  • CF2065D Skibidus and Sigma
  • 微信二次开发个人号api
  • 深入解析:神经网络二分类任务详解:前向传播与反向传播的数学计算
  • 课后作业2(动手动脑,课后实验性问题)
  • 从零开始构建图注意力网络:GAT算法原理与数值实现详解
  • 分解原则编写
  • 关于Leetcode 812题的简单思考
  • Laravel5.8 利用 snappyPDF 生成PDF文件
  • 数据结构——链表 - 详解
  • 25秋周总结4
  • Python 潮流周刊#121:工程师如何做出高效决策?
  • 饥荒联机版
  • LinuxC++项目开发日志——基于正倒排索引的boost搜索引擎(5——通过cpp-httplib库建立网页模块) - 详解
  • iSCSI网络存储——基于VM17下麒麟V10SP1与SP2的共享配置
  • 微信二次开发文档