0

NOTE: I have asked a question before and got marked as duplicate with a link, the answers in the link were for if you had the full URL, as I am asking just for if I have just the query.

In node.js I have a string that looks like this: "color=green&name=Joey&age=126" and want to turn it into an object like this {color:"green",name:"Joey",age:"126"}. This string is received via the POST method. Here is what I have tried and which does not work.

var post = "color=lime+green&name=Joey&age=126";
var parsed = JSON.parse('{"' + post.replace(/=/g, '":"').replace(/&/g, '","') + '"}');
console.log(parsed);

It would help me a lot if I could get a proper and safe way to do this. Also, because of how I have set up my node, I can't use any modules other than HTTP, fs, and URL.

Haydan Fisher
  • 73
  • 2
  • 5
  • possible duplicate of: https://stackoverflow.com/questions/8648892/how-to-convert-url-parameters-to-a-javascript-object – Amir Saleem Jun 15 '21 at 03:49
  • The second answer in that dupe points out the QueryString module. You can pass your string to `querystring.parse("color=lime+green&name=Joey&age=126")` and get your object. That module is also the first thing that pops up when you query "node parse query string". – Mark Jun 15 '21 at 03:49
  • https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options – StackOverMySoul Jun 15 '21 at 03:51
  • Would I have to require('querystring') in order to use that or is it built in as one of the modules I listed? – Haydan Fisher Jun 15 '21 at 03:54
  • I think I got it, Is doing { var parsed = url.parse("localhost/nothing?" + post, true).query } a good idea? – Haydan Fisher Jun 15 '21 at 04:00
  • 1
    Yes you need something like `const querystring = require('querystring');` which you will see in the *first* code example on the docs page. – Mark Jun 15 '21 at 04:04
  • 1
    A simple Google search for "nodejs parse query string" gives you [this](https://nodejs.org/api/querystring.html) as the very first link and it contains examples. And, that link also references [this](https://nodejs.org/api/url.html#url_class_urlsearchparams) which is a different way to do it using the URL module. Why are you asking your second question about this without doing basic research on the topic first? – jfriend00 Jun 15 '21 at 04:15
  • Sorry jfriend, I did do research but the thing I was missing from my google search was "string". This will work just fine for what I am doing. – Haydan Fisher Jun 15 '21 at 04:26

0 Answers0