javascript - 创建 json 数组并将其写入文件

标签 javascript php html json

我是 json、php 和 javascript 新手。我想将表单数据保存在 json 文件中。我使用 html 和 javascript 创建了一个表单,并创建了一个 ajax 请求来将其发布到 php。在我的 php 文件中,我计划将其写入文件。现在我的代码可以工作,但我想将其设为 json 数组。这就是我现在所拥有的。

{
"Brand": "Ferrari",
"Model": "458 Italia",
"Year": "2010 - 2015",
"body": "2-seat Berlinetta, 2-seat Spider",
"engine": "4.5L Ferrari F136F V8",
"power": "562bhp @9000rpm",
"torque": "540nm @6000rpm",
"transmission": "7-speed dual clutch",
"topSpeed": "325kph",
"acceleration": "3.3 sec"
}

但我想这样做。

{
"cars": [
    "Brand": "Ferrari",
    "Model": "458 Italia",
    "Year": "2010 - 2015",
    "body": "2-seat Berlinetta, 2-seat Spider",
    "engine": "4.5L Ferrari F136F V8",
    "power": "562bhp @9000rpm",
    "torque": "540nm @6000rpm",
    "transmission": "7-speed dual clutch",
    "topSpeed": "325kph",
    "acceleration": "3.3 sec"]
}

我应该在我的 php 文件中执行它吗?有什么建议我应该采取哪种方式?通知您这是我的 php 文件

<?php
$json = $_POST['json'];
$info = json_encode($json, JSON_PRETTY_PRINT);

$file = fopen('cars.txt', 'a');
fwrite($file, "\n". $info);
fclose($file);
?>

最后一个问题,正如你所看到的,我正在使用 .txt 文件,我可以将其转换为 .json 文件吗?它会改变什么吗?谢谢大家的关注。

最佳答案

在这种情况下,您还必须使用json_decode

<?php
   $json = $_POST["json"];
   $decode = json_decode($json);

   if (!$decode) {
       exit(); // invalid JSON.
   }

   $final = array(
      "cars" => $decode
   );

   file_put_contents("filename.json", json_encode($final, JSON_PRETTY_PRINT));
?>

关于javascript - 创建 json 数组并将其写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38109455/

相关文章:

javascript - 在本地保存 JSON 文件

php - mySQL 连接无法正常工作

php - 从 URL 抓取 HEX - PHP

jquery - 如何制作这个 jQuery/CSS 动画

html - &lt;header&gt; 与 <head>

javascript - 使用拦截器延迟所有请求

javascript - 如何在客户端sdk中提交带有payload.nonce的表单?我正在使用 Braintree 给出的示例?

javascript - 在 native react 中隐藏条件 View

php - 关于在 php 脚本中释放内存的问题

javascript - 运行 Google Web 应用程序脚本后出现空白屏幕