Home > Back-end >  How to validly parse a non JSON conform stringified data format into an object?
How to validly parse a non JSON conform stringified data format into an object?

Time:07-28

I wanna know if i can convert

let serverProps = "{
server-name: New Server,
server-id: 165894343,
server-description: New Server Description,
server-avatar: ./server_avatars/165894343AEAVATAR.jpg,
server-banner: 0
};"

To an object please help

CodePudding user response:

The best solution is to fix whatever is outputting your code into a proper JSON format.

But for this you can split on new lines. Loop over that and split on colon and build your object.

const serverProps = `{
server-name: New Server,
server-id: 165894343,
server-description: New Server Description,
server-avatar: ./server_avatars/165894343AEAVATAR.jpg,
server-banner: 0
};`

const out = serverProps.split(/,?\n/).reduce((o, line) => {
  const [key, value] = line.split(/\s?:\s?/);
  if (value) {
    o[key] = value
  }
  return o;
}, {});
console.log(out);

CodePudding user response:

In case of a multiline format like the one given by the OP one could come up with a two folded regex based approach.

const serverProps = `{
server-name: New Server,
server-id: 165894343,
server-description: New Server Description,
server-avatar: ./server_avatars/165894343AEAVATAR.jpg,
server-banner: 0
};`;

console.log(
  'serverProps ...', serverProps
);
console.log(
  'no braces serverProps ...', serverProps
    .replace((/^{\n|\n}.*$/gm), '')
);
console.log(
  'result ...', Array
    .from(
      serverProps
        // see ... [https://regex101.com/r/tgYr1x/4]
        .replace((/^{\n|\n}.*$/gm), '')
        // see ... [https://regex101.com/r/tgYr1x/1]
        .matchAll(/^\s*(?<key>[^:] ?)\s*:\s*(?<value>.*?),*$/gm)
    )
    .reduce((merger, { groups: { key, value } }) =>
      Object.assign(merger, { [ key ]: value }), {}
    )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

CodePudding user response:

Your JSON format seems incorrect! but for reference:

You can simply use

JSON.parse(your_string);

example:

JSON.parse('{ "name" : "testuser" }')

results:

{ name: 'testuser' }

For reverse JSON.stringify() is used

link for reference:

  • Related