javascript - 从 json 键导出一些值作为新的 json 对象

标签 javascript php json

坚持将此 javascipt 代码(从 SO)“转换”为 php。

考虑 "AAA='111' BBB='222' DD='333' CC='dao@toto.fr'" 来自先前 json 对象键的值。

1 - 从一些 API 帖子中收到此 json

{
  "first_key": "first_value",
  "sec_key": "sec_value",
  "third_key": "AAA='111' BBB='222' DD='333' CC='dao@toto.fr'",
}

2 - 期望像这样将 Third_key 值导出为新的 json

{ "AAA": "111", "BBB": "222", "DD": "333", "CC": "dao@toto.fr" }

所以,

<body>
<script type="text/javascript">

var input="AAA='111' BBB='222' DD='333' CC='dao@toto.fr'";
var result={};
 input.split("'").forEach(function(value,i,arr){
  if(i%2===0) return;
  var key=arr[i-1].trim().replace("=","");
  result[key]=value;
});

 console.log(result);
</script>
</body>

在控制台中得到这个,大约是我想要的:

Object { AAA: "111", BBB: "222", DD: "333", CC: "dao@toto.fr" }

预期输出:

Object { "AAA": "111", "BBB": "222", "DD": "333", "CC": "dao@toto.fr" }

如何在 PHP 中获得预期的输出?搜索引擎将我发送到与我要查找的内容无关的 json_encode/json_decode 函数。

最佳答案

在 PHP 中,您可以非常简单地使用正则表达式来提取名称和值,然后使用 array_combine() 将其结果组合到关联数组中,然后使用 json_encode( ) 结果数组...

$third_key = "AAA='111' BBB='222' DD='333' CC='dao@toto.fr'";
preg_match_all("/(\w*)='(.*?)'/", $third_key, $matches);

print_r($matches);

echo json_encode(array_combine($matches[1], $matches[2]));

这给出了...

Array
(
    [0] => Array
        (
            [0] => AAA='111'
            [1] => BBB='222'
            [2] => DD='333'
            [3] => CC='dao@toto.fr'
        )

    [1] => Array
        (
            [0] => AAA
            [1] => BBB
            [2] => DD
            [3] => CC
        )

    [2] => Array
        (
            [0] => 111
            [1] => 222
            [2] => 333
            [3] => dao@toto.fr
        )

)
{"AAA":"111","BBB":"222","DD":"333","CC":"dao@toto.fr"}

print_r($matches); 只是为了展示正则表达式如何将原始字符串拆分成它的部分,以及最后一行如何创建结束数组。

关于javascript - 从 json 键导出一些值作为新的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55678919/

相关文章:

php - 导航栏没有使用 Bootstrap 4 的样式

php - 搜索工作正常,只有第一个结果未显示

php - PDO SQLSRV 和 PDO MySQL 在获取 int 或 float 时返回字符串

json - 编码类型时如何将方法结果嵌入到 JSON 输出中?

java - GET 请求正文中的 RESTful Web 服务和 JSON 文档

javascript - 添加 "required"到选择框

javascript - 如何在 JavaScript 中验证当前日期的一个日期?

javascript - Nuxt 3 包导入说明符 "#internal/nitro"未定义

javascript - Javascript 中的 (function e(t,n,r){ ...}) 是什么?

php - 如何从传入的 JSON 数据生成表 [Laravel、Ajax]