将数据以正确的格式保存到JSON文件中——PHP

时间:2023-01-14 10:31:58

I am currently saving click co-ordinates to a JSON file through the use of the following code:

目前,我正在通过使用以下代码来保存单击坐标到JSON文件:

onmouseup = function(e){
  var Clicks = {};
  Clicks.state = {
    cX: e.clientX,
    cY: e.clientY,
  }
  $.ajax({
    type : "GET",
    url : "PHP/save_json.php",
    data : {
      state : JSON.stringify(Clicks.state)
    }
  });
}

<?php
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
fwrite($fh, $stringData);
fclose($fh)
?>

However with the above code I am saving the coordinates in the following incorrect format:

但是,使用上述代码,我将以以下不正确的格式保存坐标:

{"cX":467,"cY":374}{"cX":56,"cY":474}

{“cX”:467年,“cY”:374 } {“cX”:56岁“cY”:474 }

Can anyone please help me to save the coordinates in a JSON array rather than in seperate JSON entries?

谁能帮我将坐标保存在JSON数组中而不是分离JSON条目中?

I would like the file to be as follows, were the coordinates are added onto the already existing JSON array within the file:

如果将坐标添加到文件中已有的JSON数组中,我希望文件如下:

{ 
   "ID":["1","2"],
   "cX":["467","56"],
   "cY":["374","474"]
}

4 个解决方案

#1


1  

What you need to do is:

你需要做的是:

  • Open the clicks.json file and read the entire contents.
  • 点击打开。json文件并读取整个内容。
  • Turn this into an instance of stdClass by using json_decode. This will give you a PHP object that you can modify using normal PHP functions and syntax.
  • 通过使用json_decode将其转换为stdClass实例。这将为您提供一个PHP对象,您可以使用普通的PHP函数和语法对其进行修改。
  • Use json_decode on the JSON that you receive from your client.
  • 在从客户端接收的JSON上使用json_decode。
  • Use array_push to push the new values from the client into the arrays stored in the file (something like array_push($fileJson->cX, $clientJson->cX);)
  • 使用array_push将新值从客户端推入文件中存储的数组(类似array_push($fileJson->cX, $clientJson->cX);)
  • Use json_encode to encode $fileJson again.
  • 再次使用json_encode对$fileJson进行编码。
  • Write it back to the file.
  • 把它写回文件。

This assumes that the clicks.json file is already correctly formatted JSON with the arrays already created etc.

这假设点击。json文件已经用已经创建的数组正确地格式化了json。

#2


1  

Given the current arrangement of the key and value bits, it's apparent that some sort of transformation is needed in the JSON data before it is written to the file. Where this transformation is done is definitely a matter of an opinion. However, assuming that you receive following JSON data in PHP:

考虑到键和值位的当前排列,很明显,在将JSON数据写入文件之前,需要在JSON数据中进行某种转换。这种转变发生在哪里,绝对是一个观点问题。但是,假设您在PHP中接收到以下JSON数据:

[{"cX":467,"cY":374},{"cX":56,"cY":474}]

The PHP code can be written as (illustrated with static input):

PHP代码可以写成(用静态输入进行说明):

$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
$json_array_source  =   json_decode($string, true);

$json_array_target  =   array();
foreach($json_array_source as $key=>$value){
    $json_array_target["ID"][]  =   $key + 1;
    foreach($value as $sub_key => $sub_value){
        $json_array_target[$sub_key][]  =   $sub_value;
    }
}

$transformed_string = json_encode($json_array_target);
fwrite($fh, $transformed_string);
fclose($fh);

If you were to echo $transformed_string;, you'd see:

如果您要回显$transformed_string;,您将看到:

{"ID":[1,2],"cX":[467,56],"cY":[374,474]}

Which is what will be written to the file.

它将被写入文件。

#3


1  

You need load data to array, add new data and save back to file.

需要将数据加载到数组中,添加新数据并将其保存到文件中。

I think you don't need save numbers in strings. These code create new file if not exists.

我认为你不需要在字符串中保存数字。如果不存在,这些代码将创建新的文件。

<?php
// test input data
if(isset($_GET['state']['cX']) && 
   isset($_GET['state']['cY']) && 
   is_numeric($_GET['state']['cX']) && 
   is_numeric($_GET['state']['cY']) ) 
{
    // ok
} else {
   exit('Bad data format');
}

$myFile = __DIR__ . "/JSON/clicks.json";

// step 1, load data from file to array
$array = file_exists($myFile) ? 
    json_decode(file_get_contents($myFile), true) : 
    [];

// step 2, add data to array
$array['ID'][] = isset($array['ID']) ? (count($array['ID']) + 1) : 1;
$array['cX'][] = (int) $state['cX'];
$array['cY'][] = (int) $state['cY'];

// step 3, save array back to file
file_put_contents($myFile, json_encode($array));

Or you can use other file format where will be possible to append file. The easiest format for static structured data could be CSV

或者你也可以使用其他的文件格式来附加文件。静态结构化数据最简单的格式可能是CSV。

#4


-1  

Use json_encode to convert your string to an object, then convert it back to a string using json_decode and the JSON_PRETTY_PRINT option.

使用json_encode将字符串转换为对象,然后使用json_decode和JSON_PRETTY_PRINT选项将其转换为字符串。

$stringData = json_decode(json_encode($_GET["state"]), JSON_PRETTY_PRINT);

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/function.json-encode.php

#1


1  

What you need to do is:

你需要做的是:

  • Open the clicks.json file and read the entire contents.
  • 点击打开。json文件并读取整个内容。
  • Turn this into an instance of stdClass by using json_decode. This will give you a PHP object that you can modify using normal PHP functions and syntax.
  • 通过使用json_decode将其转换为stdClass实例。这将为您提供一个PHP对象,您可以使用普通的PHP函数和语法对其进行修改。
  • Use json_decode on the JSON that you receive from your client.
  • 在从客户端接收的JSON上使用json_decode。
  • Use array_push to push the new values from the client into the arrays stored in the file (something like array_push($fileJson->cX, $clientJson->cX);)
  • 使用array_push将新值从客户端推入文件中存储的数组(类似array_push($fileJson->cX, $clientJson->cX);)
  • Use json_encode to encode $fileJson again.
  • 再次使用json_encode对$fileJson进行编码。
  • Write it back to the file.
  • 把它写回文件。

This assumes that the clicks.json file is already correctly formatted JSON with the arrays already created etc.

这假设点击。json文件已经用已经创建的数组正确地格式化了json。

#2


1  

Given the current arrangement of the key and value bits, it's apparent that some sort of transformation is needed in the JSON data before it is written to the file. Where this transformation is done is definitely a matter of an opinion. However, assuming that you receive following JSON data in PHP:

考虑到键和值位的当前排列,很明显,在将JSON数据写入文件之前,需要在JSON数据中进行某种转换。这种转变发生在哪里,绝对是一个观点问题。但是,假设您在PHP中接收到以下JSON数据:

[{"cX":467,"cY":374},{"cX":56,"cY":474}]

The PHP code can be written as (illustrated with static input):

PHP代码可以写成(用静态输入进行说明):

$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
$json_array_source  =   json_decode($string, true);

$json_array_target  =   array();
foreach($json_array_source as $key=>$value){
    $json_array_target["ID"][]  =   $key + 1;
    foreach($value as $sub_key => $sub_value){
        $json_array_target[$sub_key][]  =   $sub_value;
    }
}

$transformed_string = json_encode($json_array_target);
fwrite($fh, $transformed_string);
fclose($fh);

If you were to echo $transformed_string;, you'd see:

如果您要回显$transformed_string;,您将看到:

{"ID":[1,2],"cX":[467,56],"cY":[374,474]}

Which is what will be written to the file.

它将被写入文件。

#3


1  

You need load data to array, add new data and save back to file.

需要将数据加载到数组中,添加新数据并将其保存到文件中。

I think you don't need save numbers in strings. These code create new file if not exists.

我认为你不需要在字符串中保存数字。如果不存在,这些代码将创建新的文件。

<?php
// test input data
if(isset($_GET['state']['cX']) && 
   isset($_GET['state']['cY']) && 
   is_numeric($_GET['state']['cX']) && 
   is_numeric($_GET['state']['cY']) ) 
{
    // ok
} else {
   exit('Bad data format');
}

$myFile = __DIR__ . "/JSON/clicks.json";

// step 1, load data from file to array
$array = file_exists($myFile) ? 
    json_decode(file_get_contents($myFile), true) : 
    [];

// step 2, add data to array
$array['ID'][] = isset($array['ID']) ? (count($array['ID']) + 1) : 1;
$array['cX'][] = (int) $state['cX'];
$array['cY'][] = (int) $state['cY'];

// step 3, save array back to file
file_put_contents($myFile, json_encode($array));

Or you can use other file format where will be possible to append file. The easiest format for static structured data could be CSV

或者你也可以使用其他的文件格式来附加文件。静态结构化数据最简单的格式可能是CSV。

#4


-1  

Use json_encode to convert your string to an object, then convert it back to a string using json_decode and the JSON_PRETTY_PRINT option.

使用json_encode将字符串转换为对象,然后使用json_decode和JSON_PRETTY_PRINT选项将其转换为字符串。

$stringData = json_decode(json_encode($_GET["state"]), JSON_PRETTY_PRINT);

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/function.json-encode.php