JSON5是JSON語法的擴(kuò)展,旨在提高開發(fā)者編寫和處理數(shù)據(jù)的便利性,方便開發(fā)者編寫和維護(hù)JSON配置文件。JSON5解除一些標(biāo)準(zhǔn)JSON的限制,諸如不支持注釋,不支持字符串換行,所有的key都必須雙引號,數(shù)組的最后一個元素不能有多余的逗號…等等。下面是JSON5的主要特點:
允許注釋:
JSON5允許在代碼中添加單行(//)和多行(/* */)注釋,添加注釋,讓數(shù)據(jù)閱讀起來更容器。
鍵名更自由:
鍵名可以不用引號括起來,Unicode字符也可以作為鍵名,鍵名允許重復(fù),后面的會覆蓋前面的。
尾隨逗號:
在對象和數(shù)組的最后一個元素后面可以允許有逗號,這使得添加、刪除和移動項目變得更容易。
數(shù)字增強:
- 支持十六進(jìn)制表示法(如0xff5643)
- 允許數(shù)字以小數(shù)點開始或結(jié)束(如.5或5.)
- 支持正負(fù)無窮大(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的官方標(biāo)準(zhǔn)。在使用JSON5時,需要確保你的解析器和環(huán)境支持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 解析結(jié)果:");
Console.WriteLine(json5Obj);
// 將 JSON5 對象轉(zhuǎn)換為標(biāo)準(zhǔn) JSON 字符串
string standardJsonStr = JSON5.Stringify(json5Obj, new JSON5.JSON5Options { Indent = " " });
Console.WriteLine("\nJSON5 轉(zhuǎn)換為標(biāo)準(zhǔn) JSON:");
Console.WriteLine(standardJsonStr);
// 展示 JSON5 的特性
Console.WriteLine("\nJSON5 特性:");
Console.WriteLine($"支持注釋: {json5Str.Contains("http:// 這是一個注釋")}");
Console.WriteLine($"支持未加引號的鍵: {json5Str.Contains("unquoted:")}");
Console.WriteLine($"支持單引號: {json5Str.Contains("'and you can quote me on that'")}");
Console.WriteLine($"支持多行字符串: {json5Str.Contains("Look, Mom! \\")}");
Console.WriteLine($"支持十六進(jìn)制: {json5Str.Contains("0xdecaf")}");
Console.WriteLine($"支持特殊數(shù)值 (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 解析標(biāo)準(zhǔn) JSON
JObject newtonsoftObj = JsonConvert.DeserializeObject(json5Str);
Console.WriteLine("Newtonsoft.Json 解析結(jié)果:");
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($"支持動態(tài)類型 (dynamic): {((dynamic)newtonsoftObj).singleQuotes}");
}
}
JSONC (JSON with comments) 是JSON格式的一個擴(kuò)展,它允許在JSON中添加注釋。
JSONC是由微軟創(chuàng)建,并在VS Code中使用,vscode的`settings.json`配置文件,就使用jsonc語法。
JSON5是一個定義明確的規(guī)范,包括注釋、尾隨逗號、多行字符串、單引號或雙引號、無引號的對象鍵,以及其他借鑒自ECMAScript
5.1的特性。它是JavaScript的嚴(yán)格子集,并且易于理解。
更多推薦
JSON數(shù)據(jù)提取、查詢
JSON Web Tokens