Javascript 将 JSON 对象写入服务器上的 .json 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3921520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing JSON object to .json file on server
提问by Hristo
I'm trying to write my JSON object to a .json file on the server. The way I'm doing this now is:
我正在尝试将我的 JSON 对象写入服务器上的 .json 文件。我现在这样做的方式是:
JavaScript:
JavaScript:
function createJsonFile() {
var jsonObject = {
"metros" : [],
"routes" : []
};
// write cities to JSON Object
for ( var index = 0; index < graph.getVerticies().length; index++) {
jsonObject.metros[index] = JSON.stringify(graph.getVertex(index).getData());
}
// write routes to JSON Object
for ( var index = 0; index < graph.getEdges().length; index++) {
jsonObject.routes[index] = JSON.stringify(graph.getEdge(index));
}
// some jQuery to write to file
$.ajax({
type : "POST",
url : "json.php",
dataType : 'json',
data : {
json : jsonObject
}
});
};
PHP:
PHP:
<?php
$json = $_POST['json'];
$info = json_encode($json);
$file = fopen('new_map_data.json','w+');
fwrite($file, $info);
fclose($file);
?>
It is writing fine and the information seems to be correct, but it is not rendering properly. It is coming out as:
它写得很好,信息似乎是正确的,但它没有正确呈现。它出来了:
{"metros":["{\\"code\\":\\"SCL\\",\\"name\\":\\"Santiago\\",\\"country\\":\\"CL\\",\\"continent\\":\\"South America\\",\\"timezone\\":-4,\\"coordinates\\":{\\"S\\":33,\\"W\\":71},\\"population\\":6000000,\\"region\\":1}",
... but I'm expecting this:
......但我期待这个:
"metros" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
} ,
Why am I getting all of these slashes and why it is all on one line?
为什么我得到所有这些斜杠,为什么它们都在一行上?
回答by Tomalak
You are double-encoding. There is no need to encode in JS andPHP, just do it on one side, and just do it once.
你是双重编码。不需要用JS和PHP编码,一边做,一次就做。
// step 1: build data structure
var data = {
metros: graph.getVerticies(),
routes: graph.getEdges()
}
// step 2: convert data structure to JSON
$.ajax({
type : "POST",
url : "json.php",
data : {
json : JSON.stringify(data)
}
});
Note that the dataType
parameter denotes the expected responsetype, not the the type you send the data as. Post requests will be sent as application/x-www-form-urlencoded
by default.
请注意,该dataType
参数表示预期的响应类型,而不是您发送数据的类型。application/x-www-form-urlencoded
默认情况下将发送 Post 请求。
I don't think you need that parameter at all. You could trim that down to:
我认为您根本不需要该参数。您可以将其缩减为:
$.post("json.php", {json : JSON.stringify(data)});
Then (in PHP) do:
然后(在 PHP 中)执行:
<?php
$json = $_POST['json'];
/* sanity check */
if (json_decode($json) != null)
{
$file = fopen('new_map_data.json','w+');
fwrite($file, $json);
fclose($file);
}
else
{
// user has posted invalid JSON, handle the error
}
?>
回答by Alin Purcaru
Don't JSON.stringify
. You get a double JSON encoding by doing that.
不要JSON.stringify
。通过这样做,您将获得双重 JSON 编码。
You first convert your array elements to a JSON string, then you add them to your full object, and then you encode your big object, but when encoding the elements already encoded are treated as simple strings so all the special chars are escaped. You need to have one big object and encode it just once. The encoder will take care of the children.
您首先将数组元素转换为 JSON 字符串,然后将它们添加到完整对象中,然后对大对象进行编码,但是在编码时,已编码的元素被视为简单字符串,因此所有特殊字符都将被转义。您需要拥有一个大对象并对其进行一次编码。编码器会照顾孩子。
For the on row problem try sending a JSON data type header: Content-type: text/json
I think (didn't google for it). But rendering will depend only on your browser. Also it may be possible to encode with indentation.
对于行上的问题,请尝试发送 JSON 数据类型标头:Content-type: text/json
我认为(没有用谷歌搜索)。但是渲染将仅取决于您的浏览器。也可以使用缩进进行编码。
回答by Suveer Jacob
Probably too late to answer the question. But I encountered the same issue. I resolved it by using "JSON_PRETTY_PRINT"
可能来不及回答这个问题了。但我遇到了同样的问题。我使用“JSON_PRETTY_PRINT”解决了它
Following is my code:
以下是我的代码:
<?php
if(isset($_POST['object'])) {
$json = json_encode($_POST['object'],JSON_PRETTY_PRINT);
$fp = fopen('results.json', 'w');
fwrite($fp, $json);
fclose($fp);
} else {
echo "Object Not Received";
}
?>
回答by sudheer suri
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
<?php
$str = file_get_contents('data.json');//get contents of your json file and store it in a string
$arr = json_decode($str, true);//decode it
$arrne['name'] = "sadaadad";
$arrne['password'] = "sadaadad";
$arrne['nickname'] = "sadaadad";
array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
$str = json_encode($arr);
//now send evrything to ur data.json file using folowing code
if (json_decode($str) != null)
{
$file = fopen('data.json','w');
fwrite($file, $str);
fclose($file);
}
else
{
// invalid JSON, handle the error
}
?>
<form method=>
</body>
data.json
数据.json
{
"employees":[
{
"email":"11BD1A05G9",
"password":"INTRODUCTION TO ANALYTICS",
"nickname":4
},
{
"email":"Betty",
"password":"Layers",
"nickname":4
},
{
"email":"Carl",
"password":"Louis",
"nickname":4
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
}
]
}