#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define lines 4000
/* reads every 4000 lines
of the file or the whole file*/
void read_the_file(string &str, ifstream &in)
{
string line;
int pos = 0;
while (pos <= lines && !in.eof()) {
getline(in, line);
str += line;
pos++;
}
}
/* jumpes over whitespaces */
size_t eat_whitespace(const string &str, size_t pos)
{
while (str[pos] == ' ' || str[pos] == '\t' || str[pos] == '\n') {
pos++;
}
return pos;
}
/* saves the keys of the first obj
&& prints string values (between quotes)*/
void inside_quote (const string &str, string &keys, size_t &pos,
bool quote_closed, bool first_object, ofstream &file)
{
quote_closed = !quote_closed;
if (quote_closed == false) {
pos++;
while (str[pos] != '\"') {
if (first_object == true) {
keys += str[pos];
} else {
file << str[pos];
}
pos++;
}
}
quote_closed = true;
}
/* gets the values (int or string)*/
bool get_values (const string &str, string &values, size_t &pos,
bool quote_closed, bool first_object, ofstream &file)
{
bool value_closed = false;
pos = eat_whitespace(str, pos + 1);
while (str[pos] != ',' && str[pos] != '}' && pos != str.length()) {
if (str[pos] != '\"' && quote_closed == true &&
str[pos] != ' ' && str[pos] != '\n') {
if (first_object == true) {
values += str[pos];
} else {
file << str[pos];
}
} else if (str[pos] == '\"') {
inside_quote (str, values, pos, quote_closed, first_object, file);
}
pos++;
}
if (str[pos] == ',' || str[pos] == '}') {
value_closed = true;
if (first_object == true) {
values += ',';
} else {
file << ",";
}
}
return value_closed;
}
/* prints the keys of first obj
&& all values */
bool find_pairs(const string &str, int &obj, ofstream &out,
string &keys, string &values, bool quote_closed)
{
size_t length = str.length();
size_t i = 0;
bool value_closed = false;
while (i < length) {
if (str[i] == '\"' && obj == 0) {
inside_quote (str, keys, i, quote_closed, true, out);
keys += ',';
} else if (str [i] == ':' && obj == 0) {
value_closed = get_values(str, values, i, quote_closed, true, out);
} else if (str [i] == ':') {
value_closed = get_values(str, values, i, quote_closed, false, out);
}
if (quote_closed == true && str[i] == '}') {
if (obj == 0) {
out << keys << endl;
}
obj++;
out << values << endl;
values.clear();
}
i++;
}
return value_closed;
}
int main()
{
ifstream in("convertor.in");
ofstream out("convertor.out");
int obj = 0;
bool value_closed, quote_closed = true;
string str, keys, values;
read_the_file(str, in);
value_closed = find_pairs(str, obj, out, keys, values, quote_closed);
/*while we didn't reach eof read
another 4000 lines/rest of the file*/
while (!in.eof()) {
if (value_closed) {
str.clear();
/* case when ':' and the value
are in separate chunks */
} else {
int i = str.find_last_of (':');
string sub_string = str.substr (i, str.length() - i + 1);
str.clear();
str += sub_string;
}
read_the_file(str, in);
value_closed = find_pairs(str, obj, out, keys, values, quote_closed);
}
}