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
  • 145
  • 2
  • 20

5 Answers5

6

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,500
  • 1
  • 25
  • 42
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
  • 907
  • 5
  • 19
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
  • 101
  • 3
  • 11
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
  • 472
  • 2
  • 7
  • 13
1

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
  • 25,196
  • 9
  • 41
  • 59
lucas
  • 1,027
  • 8
  • 14