我几乎 100% 有我需要做的事情。它正在从 csv 转换为 JSON。 变量 RESULT 它像这样(如下)出现在控制台上:它错过了标题名称中的“”。 我收到了错误的请求 400。但我不明白为什么我正在传递一个变量 - JSON 的结果
结果 Json 日志
{Time: Array(3), Yaw: Array(3), Pitch: Array(3), Roll: Array(3), Heading: Array(3), …}
Ax: (3) [-0.42, -0.41, -0.41]
Ay: (3) [-0.15, -0.13, -0.1]
Az: (3) [0.9, 0.91, 1]
Gx: (3) [0, 0, -0]
Gy: (3) [-0.01, -0, -0.01]
Gz: (3) [0.02, 0.02, 0.02]
Heading: (3) [-3.24, -3.25, -3.17]
Mx: (3) [0.26, 0.26, 0.26]
My: (3) [0.01, 0.01, 0.01]
Mz: (3) [-0.04, -0.04, -0.07]
Pitch: (3) [0.36, 0.76, 1.08]
Roll: (3) [-0.13, -0.25, -0.35]
Time: (3) [1364, 1374, 1384]
Yaw: (3) [0.15, 0.3, 0.45]
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swim Api read csv</title>
</head>
<body>
<p>Select local CSV File:</p>
<input name="myFile" type="file">
<button id="convertBtn" onclick="ConvertFile()">Convert and send to MongoDB</button>
<script src="bundle.js"></script>
</body>
</html>
bundle.js
ConvertFile = function () {
var input = document.querySelector('input').files;
if(!input.length){
alert("No file selected");
return;
}
var file = input[0];
var reader = new FileReader();
reader.onload = (function() {
return function(e) {
var fileData = e.target.result.trim().split('\n').map(row => row.split(','));
var HEADERS = ["Time", "Yaw", "Pitch", "Roll", "Heading", "Ax", "Ay", "Az", "Gx", "Gy", "Gz", "Mx", "My", "Mz"];
const RESULT = {};
// Assign every heading to the result.
for (const HEADING of HEADERS) RESULT[HEADING] = [];
fileData.map(row =>
// Each row → each column, number of columns === number of headers
row.map((column, i) =>
RESULT[HEADERS[i]]
.push(Number(column))
)
);
console.log(RESULT);
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://127.0.0.1:8080/data/add' );
xhr.responseType = 'json';
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(RESULT);
};
})(file);
reader.readAsText(file);;
};
views.py
from flask import jsonify, render_template, request
from flask import Flask
import pymongo
import json
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
client = pymongo.MongoClient("mongodb+srv://****:****@*****.****.mongodb.net/*****?retryWrites=true&w=majority")
db = client['*****']
collection = db['*****']
@app.route("/")
def index():
return render_template("index.html")
@app.route("/data/add", methods=['POST'])
def insert_document():
req_data = request.get_json()
collection.insert_one(req_data).inserted_id
return "data sent to database", 200
if __name__ == '__main__':
app.run(debug=True, port=8080)