javascript - 将 yaml 字符串转换为 JSON 对象

标签 javascript php json yaml

我们有两个独立的代码库,它们使用不同的本地化风格。其中一个代码库使用 yaml,另一个使用 JSON。

现在,我们正在慢慢迁移到使用 JSON 的代码库,但是有 20k yaml 字符串和 7 种不同的语言,手动转换这些是一件很痛苦的事情。不幸的是,我们在我们的 yaml 文件中使用字符串表示法而不是对象表示法,所以像 this 这样的转换器行不通。

示例 yaml

cart.title.primary: Cart
cart.title.secondary: Buy products
cart.dialog.title: Remove product
cart.dialog.text: Are you sure to remove this product?

成为转换器中的this

{
  "cart.title.primary": "Cart",
  "cart.title.secondary": "Buy products",
  "cart.dialog.title": "Remove product",
  "cart.dialog.text": "Are you sure to remove this product?"
}

但我想要的是,字符串中的每个点实际上是 JSON 中的一个对象。所以理想情况下,我提供的 yaml 应该是这样的:

{
  "cart": {
    "title": {
      "primary": "Cart",
      "secondary: "Buy Products"
    },
    "dialog": {
      "title": "Remove product",
      "text": "Are you sure to remove this product?"
    }
  }
}

有没有人有做这样的事情的经验?首长。使用 PHP 或 JavaScript。提前致谢!

最佳答案

您可以结合使用 yaml 的基本加载,这只是假定一个字符串并使用 yaml_parse() ,然后使用 Convert dot syntax like "this.that.other" to multi-dimensional array in PHP 中的代码您可以一次处理每一行以创建新结构...

$yaml = 'cart.title.primary: Cart
cart.title.secondary: Buy products
cart.dialog.title: Remove product
cart.dialog.text: Are you sure to remove this product?';

$data = yaml_parse($yaml);

$output = [];
foreach ( $data as $key => $entry ) {
    assignArrayByPath($output, $key, $entry);
}

function assignArrayByPath(&$arr, $path, $value, $separator='.') {
    $keys = explode($separator, $path);

    foreach ($keys as $key) {
        $arr = &$arr[$key];
    }

    $arr = $value;
}

echo json_encode($output, JSON_PRETTY_PRINT);

这给了你

{
    "cart": {
        "title": {
            "primary": "Cart",
            "secondary": "Buy products"
        },
        "dialog": {
            "title": "Remove product",
            "text": "Are you sure to remove this product?"
        }
    }
}

关于javascript - 将 yaml 字符串转换为 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014423/

相关文章:

json - Map<int, List<int>> 转换为可编码对象失败

java - 将json对象解析为android字符串

javascript - 如何在初始页面加载之前加载 CSS 数据主题以防止主题之间闪烁?

javascript - 如何在客户端中获取 socket.io 客户端的 session ID

javascript - jQuery Accordion 菜单和复选框问题

php - 如何在我的 html 网页中启用数学运算

php - 转换数据库的日期格式

javascript - 从字符串中取出大写字母并打印它们

php - 如何检查 Wordpress 发布日期是否至少 7 天

php - 从 PHP/MySQL 本地推送数据时,CardView 不显示在我的 RecycleView 上