csv转json文件

时间:2022-10-25 17:00:11

今天因为需要帮一个同事的新闻内容录入为html, 每次手改不方便,所以就弄了个csv(excel)转json的c++程序,然后再利用ejs把它渲染成网页,打开渲染好的网页再保存(不能保存源文件,不然还是空的),就可以把内容弄成一个html了,此作mark,以下为程序

// convert.cpp
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int main() {
freopen("in.csv", "r", stdin);
freopen("json.js", "w", stdout);
string str, s[];
int g = ;
int status = ;
char ch;
str = "";
while((ch = cin.get()) != EOF) {
str += ch;
}
for(int i = ; i < str.size(); i++) {
if(status == ) {
if(str[i] == '\"') {
status = ;
} else {
s[g] += str[i];
status = ;
}
} else if(status == ) {
if(str[i] == '\"') {
if(i + >= str.size()) {
g++;
break;
} else if(str[i + ] == '\"') {
s[g] += '\"';
++i;
} else if(str[i + ] == ',') {
status = ;
++g;
++i;
} else if(str[i + ] == '\n') {
status = ;
++g;
++i;
}
} else {
s[g] += str[i];
}
} else if(status == ) {
if(str[i] == ',') {
++g;
} else if(str[i] == '\n') {
++g;
} else {
s[g] += str[i];
}
}
}
int x = ;
puts("var data = [");
string name[] = {"title", "detail", "img", "url"};
for(int i = ; i < g; i++) {
if(x == ) {
if(i == ) {
puts("\t{");
} else {
puts("\t},");
puts("\t{");
}
}
cout << "\t\t" << name[x] << ": \"" << s[i] << "\"" << (x == ? "" : ",") << endl;
x = (x + ) % ;
}
puts("\t}");
puts("]");
return ;
}