Manoj Godhani
Manoj Godhani

Reputation: 1

Json from string using regular expression

I have a string like:

const stringVar = ":20:9077f1722efa3632 :12:700 :77E:  :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"

I want to create JSON from above stringVar:

{
  ":21:" : "9077f1722efa3632",
  ":12:" :  "700",
  ":27A:":  "2/2",
  ":21A:":  "9077f1722efa3632",
  ":27:" :  "1/2",
  ":40A:":  "IRREVOCABLE"
}

So, I was thinking I could split with regular expression (":(any Of char/digit):") I would make the first part the key and the second part its value.

Upvotes: 0

Views: 138

Answers (2)

Barmar
Barmar

Reputation: 781004

The regular expression /(:\w+:)(\S+)/ matches the whole key:value pair. You can add the g modifier, and then use it in a loop to get all the matches and put them into the object.

const stringVar = ":20:9077f1722efa3632 :12:700 :77E:  :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"

var regexp = /(:\w+:)(\S+)/g;
var obj = {};
var match;
while (match = regexp.exec(stringVar)) {
  obj[match[1]] = match[2];
}
console.log(obj);

If you want to create an array of {key: ":20:", value: "9077f1722efa3632"}, you can modify the code to:

const stringVar = ":20:9077f1722efa3632 :12:700 :77E:  :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"

var regexp = /(:\w+:)(\S+)/g;
var array = [];
var match;
while (match = regexp.exec(stringVar)) {
  array.push({key: match[1], value: match[2]});
}
console.log(array);

If the values can contain space, change the regexp to:

/(:\w+:)([^:]+)\s/g

This will match anything not containing : as the value, but not include the last space.

Upvotes: 2

felixmosh
felixmosh

Reputation: 35503

You can achieve the same result without using regex.

const stringVar = ":20:9077f1722efa3632 :12:700 :77E:xxx :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE";

const result = stringVar
  .split(' ')
  .reduce((ret, current) => {
    const pos = current.indexOf(':', 1);
    ret[current.substring(0, pos + 1)] = current.substring(pos + 1);
    return ret;
  }, {});

console.log(result);

Upvotes: 0

Related Questions