user1857654
user1857654

Reputation: 283

Parsing request.body to string then create JSON

I am stuck on parsing out a string right now into a json type. I've gotten the request body down to the string but cant seem to parse the data out correctly.

What I have:

String to parse:
uniq1.data.data.data 7 bleep\nuniq2.data.data.data 4 boop\nuniq3.data.data.data 7 bleep\ntets4.data.data.data 7 bleep\nuniq5.data.data.data 7 bleep\ntest6.data.data.data 7 fgws

Would like to make the string into JSON that has the following stucture so I can insert it into a mongoose db:

name: uniq1
typeID: 7
type: bleep

name: uniq2
typeID: 4
type: boop

name: tets4
typeID: 7
type: bleep

Currently I am trying to replace all of the '\n' new lines with commas so I can parse the data out using commas but when I do the bodyText.replace( new RegExp( "\n", "g" ),",") nothing in the string changes. I'm also thinking there is probably a better way to go about this that I'm not thinking of.

Thanks for any help!

Upvotes: 0

Views: 187

Answers (2)

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

You can try this-

let str = "uniq1.data.data.data 7 bleep\nuniq2.data.data.data 4 boop\nuniq3.data.data.data 7 bleep\ntets4.data.data.data 7 bleep\nuniq5.data.data.data 7 bleep\ntest6.data.data.data 7 fgws";


const arr = str.split("\n");

const json = arr.reduce((acc, curr) => {
	const [first, typeID, type] = curr.split(" ");
	const [name] = first.split('.');
	
	acc.push({name: name, typeID, type});

	return acc;
}, []);

console.log(json);
.as-console-wrapper{min-height: 100% !important; top: 0;}

Note: I've found something like bleep\uniq5 instead of bleep\nuniq5. If the request.body sends you exactly this then you are out of luck.

Upvotes: 1

Michiel
Michiel

Reputation: 353

const a = "uniq1.data.data.data 7 bleep\nuniq2.data.data.data 4 boop\nuniq3.data.data.data 7 bleep\ntets4.data.data.data 7 bleep\nuniq5.data.data.data 7 bleep\ntest6.data.data.data 7 fgws";
const b = a.split("\n");
const c = b.map((el) => el.split(" "));
const d = c.map(([name, typeID, type]) => {
  return { name, typeID, type };
});
console.log(d);

b splits the body into lines. c splits each line into an array divided by each space. d maps the array of each line into the object with the keys.

I changed the input a bit. \uniq5 this part looks inconsistent and I think it should be \nuniq5.

Upvotes: 0

Related Questions