1

How do we convert the following parameter string to JSON using node.

"token=1234&team_id=TADAS&team_domain=testddomain&channel_id=AVC"

The expected output is { "token":1234, "team_id":"TADAS","team_domain":"testddomain","channel_id":"AVC"}

Tried JSON.parse, not working - Uncaught SyntaxError: Unexpected token o in JSON at position 1

user3636388
  • 187
  • 2
  • 24

5 Answers5

7

Since no answers here are using native, URL-oriented solutions, here's my version.

You can use Node's URL module (which also works in the browser) like so :

const queryString = "token=1234&team_id=TADAS&team_domain=testddomain&channel_id=AVC";
const params = new URLSearchParams(queryString);

const paramObject = Object.fromEntries(params.entries());
    
console.log(paramObject);

Also, instead of building the object, you can simply use the get function like this :

const token = params.get("token") // Returns "1234"
Seblor
  • 6,947
  • 1
  • 25
  • 46
2

You can use the query-string package.

Usage:

const qs = require('query-string');

const query = "token=1234&team_id=TADAS&team_domain=testddomain&channel_id=AVC";

const parsedObject = qs.parse(query);
console.log(parsedObject);
huytc
  • 1,074
  • 7
  • 20
2

I think that query-string dependency is just what you need :) https://www.npmjs.com/package/query-string

The parse function takes a query string as parameter and returns a clean JS object.

KValium
  • 111
  • 1
  • 11
2

You can try using split and reduce.

const query = "token=1234&team_id=TADAS&team_domain=testddomain&channel_id=AVC"

const json = query.split('&').reduce((acc, i) => {
  const [key, value] = i.split('=')
  acc[key] = value

  return acc
}, {})

console.log(json)
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
lucas
  • 1,105
  • 8
  • 14
1

You can use querystring library of node js

var qs = require("querystring")
var json = qs.parse("token=1234&team_id=TADAS&team_domain=testddomain&channel_id=AVC")

then the output is like this

{ "token":1234, "team_id":"TADAS","team_domain":"testddomain","channel_id":"AVC"}

You can refer this link https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options

Mohit Prakash
  • 492
  • 2
  • 7
  • 15