正在分析逗号分隔的键值对



我想打开

realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*"

{
realm: "https://api.digitalocean.com/v2/registry/auth",
service: "registry.digitalocean.com",
scope: "registry:catalog:*"
}

我不知道它叫什么,但我认为应该更容易解析这些类型的格式。我想知道是否有现有的库或更简单的方法来解析这个库?

目前,我是这样做的,但我觉得这不可靠。

auth = `realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*"`;
const convertToJsonString = '{"' + auth.replace(/="/g, `":"`).replace(/",/g, `","`) + '}';
JSON.parse(convertToJsonString);

我要实现的是将Www-Authenticate标头解析为以下规范:

  • https://www.rfc-editor.org/rfc/rfc2617#section-3.2.1
  • https://datatracker.ietf.org/doc/html/rfc7235#section-4.1

我很惊讶,这种常见的东西没有现有的解析库,或者我不知道该在哪里查找。

假设所有条目的格式都很好,并且值中的",用反斜杠(",(转义,那么下面的咒语就可以了:

Object.fromEntries(
s
.replace(/(?<!\)",/g, '"n')  // replace separators by newlines
.split("n")  // split by newlines
.map((r) => /^(.+?)=(.+?)$/.exec(r))  // split by first equals
.map(([, k, v]) => [k, JSON.parse(v)]),  // parse value as JSON string
)

最新更新