我们有两个独立的代码库,它们使用不同的本地化风格。其中一个代码库使用 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/