JSON5是JSON语法的扩展,旨在提高开发者编写和处理数据的便利性,方便开发者编写和维护JSON配置文件。JSON5解除一些标准JSON的限制,诸如不支持注释,不支持字符串换行,所有的key都必须双引号,数组的最后一个元素不能有多余的逗号…等等。下面是JSON5的主要特点:
允许注释:
JSON5允许在代码中添加单行(//)和多行(/* */)注释,添加注释,让数据阅读起来更容器。
键名更自由:
键名可以不用引号括起来,Unicode字符也可以作为键名,键名允许重复,后面的会覆盖前面的。
尾随逗号:
在对象和数组的最后一个元素后面可以允许有逗号,这使得添加、删除和移动项目变得更容易。
数字增强:
- 支持十六进制表示法(如0xff5643)
- 允许数字以小数点开始或结束(如.5或5.)
- 支持正负无穷大(Infinity, -Infinity)和NaN(Not a Number)
示例(来自Chromium/Blink项目的配置文件):
{ // 这是一个注释 unquoted: 'and you can quote me on that', singleQuotes: 'I can use single quotes', lineBreaks: "Look, Mom! \ No \\n's!", hexadecimal: 0xdecaf, leadingDecimalPoint: .8675309, andTrailing: 8675309., positiveInfinity: Infinity, negativeInfinity: -Infinity, notANumber: NaN, largeNumber: 1e+100, arrayWithTrailingComma: [ 1, 2, 3, ], objectWithTrailingComma: { one: 1, two: 2, }, }
虽然JSON5更易于人类读写,但它不是JSON的官方标准。在使用JSON5时,需要确保你的解析器和环境支持JSON5格式。
JavaScript:点击查看
const JSON5 = require('json5');
const json5Str = `{
// 这是一个注释
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use single quotes',
lineBreaks: "Look, Mom! \
No \\n's!",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309,
andTrailing: 8675309.,
positiveInfinity: Infinity,
negativeInfinity: -Infinity,
notANumber: NaN,
}`;
const obj = JSON5.parse(json5Str);
console.log(obj);
const backToJson5 = JSON5.stringify(obj, null, 2);
console.log(backToJson5);
Python:点击查看
# pip3 install json5
import json5
json5_str = '''{
// 这是一个注释
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use single quotes',
lineBreaks: "Look, Mom! \
No \\n's!",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309,
andTrailing: 8675309.,
positiveInfinity: Infinity,
negativeInfinity: -Infinity,
notANumber: NaN,
}'''
obj = json5.loads(json5_str)
print(obj)
back_to_json5 = json5.dumps(obj, indent=2)
print(back_to_json5)
Ruby:点击查看
require 'json5'
json5_str = <<-JSON5
{
// 这是一个注释
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use single quotes',
lineBreaks: "Look, Mom! \
No \\n's!",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309,
andTrailing: 8675309.,
positiveInfinity: Infinity,
negativeInfinity: -Infinity,
notANumber: NaN,
}
JSON5
obj = JSON5.parse(json5_str)
puts obj
back_to_json5 = JSON5.generate(obj, indent: ' ')
puts back_to_json5
Java:点击查看
import org.json5.JSON5;
import org.json5.JSONObject;
public class JSON5Example {
public static void main(String[] args) {
String json5Str = "{\n" +
" // 这是一个注释\n" +
" unquoted: 'and you can quote me on that',\n" +
" singleQuotes: 'I can use single quotes',\n" +
" lineBreaks: \"Look, Mom! \\\n" +
"No \\n's!\",\n" +
" hexadecimal: 0xdecaf,\n" +
" leadingDecimalPoint: .8675309,\n" +
" andTrailing: 8675309.,\n" +
" positiveInfinity: Infinity,\n" +
" negativeInfinity: -Infinity,\n" +
" notANumber: NaN,\n" +
"}";
JSONObject obj = (JSONObject) JSON5.parse(json5Str);
System.out.println(obj);
String backToJson5 = JSON5.stringify(obj, null, 2);
System.out.println(backToJson5);
}
}
Java(Jackson):点击查看
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Json5Module());
JsonParser parser = new JsonFactory().createJsonParser(json5Data);
JsonNode node = mapper.readTree(parser);
C#:点击查看
using System;
using JSON5;
class Program
{
static void Main(string[] args)
{
string json5Str = @"{
// 这是一个注释
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use single quotes',
lineBreaks: ""Look, Mom! \
No \n's!"",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309,
andTrailing: 8675309.,
positiveInfinity: Infinity,
negativeInfinity: -Infinity,
notANumber: NaN,
}";
Console.WriteLine("使用 JSON5:");
// 使用 JSON5 解析
var json5Obj = JSON5.Parse(json5Str);
Console.WriteLine("JSON5 解析结果:");
Console.WriteLine(json5Obj);
// 将 JSON5 对象转换为标准 JSON 字符串
string standardJsonStr = JSON5.Stringify(json5Obj, new JSON5.JSON5Options { Indent = " " });
Console.WriteLine("\nJSON5 转换为标准 JSON:");
Console.WriteLine(standardJsonStr);
// 展示 JSON5 的特性
Console.WriteLine("\nJSON5 特性:");
Console.WriteLine($"支持注释: {json5Str.Contains("// 这是一个注释")}");
Console.WriteLine($"支持未加引号的键: {json5Str.Contains("unquoted:")}");
Console.WriteLine($"支持单引号: {json5Str.Contains("'and you can quote me on that'")}");
Console.WriteLine($"支持多行字符串: {json5Str.Contains("Look, Mom! \\")}");
Console.WriteLine($"支持十六进制: {json5Str.Contains("0xdecaf")}");
Console.WriteLine($"支持特殊数值 (Infinity, NaN): {json5Str.Contains("Infinity") && json5Str.Contains("NaN")}");
}
}
C#(Newtonsoft):点击查看
using System;
using JSON5;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string json5Str = @"{
// 这是一个注释
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use single quotes',
lineBreaks: ""Look, Mom! \
No \n's!"",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309,
andTrailing: 8675309.,
positiveInfinity: Infinity,
negativeInfinity: -Infinity,
notANumber: NaN,
}";
// 使用 Newtonsoft.Json 解析标准 JSON
JObject newtonsoftObj = JsonConvert.DeserializeObject(json5Str);
Console.WriteLine("Newtonsoft.Json 解析结果:");
Console.WriteLine(newtonsoftObj.ToString(Formatting.Indented));
// 使用 Newtonsoft.Json 序列化回 JSON 字符串
string backToJsonStr = JsonConvert.SerializeObject(newtonsoftObj, Formatting.Indented);
Console.WriteLine("\n重新序列化为 JSON:");
Console.WriteLine(backToJsonStr);
// 展示 Newtonsoft.Json 的一些功能
Console.WriteLine("\nNewtonsoft.Json 功能:");
Console.WriteLine($"可以访问特定属性: {newtonsoftObj["unquoted"]}");
Console.WriteLine($"可以修改属性: {newtonsoftObj["unquoted"] = "modified value"}");
Console.WriteLine($"支持 LINQ 查询: {newtonsoftObj.Properties().Count()} 个属性");
Console.WriteLine($"支持动态类型 (dynamic): {((dynamic)newtonsoftObj).singleQuotes}");
}
}
JSONC (JSON with comments) 是JSON格式的一个扩展,它允许在JSON中添加注释。
JSONC是由微软创建,并在VS Code中使用,vscode的`settings.json`配置文件,就使用jsonc语法。
JSON5是一个定义明确的规范,包括注释、尾随逗号、多行字符串、单引号或双引号、无引号的对象键,以及其他借鉴自ECMAScript
5.1的特性。它是JavaScript的严格子集,并且易于理解。