-3

I have this string

{"key1":"1","key2":"someString"}

I would like it to read:

{key1:1,key2:"someString"}

I can easily remove the quotes from everything. But I still need the second value with quotes around it for a graphql query in React. Sorry if my explanation in clear on why.

2 Answers2

0

To remove quotes from keys, you can use regex to replace "\w+": with with the word + colon:

let input = '{"key1":"1","key2":"someString"}';
let output = input.replace(/"(\w+)":/g, '$1:');
console.log(output);

Per question edit, it seems numeric values also want quotes removed:

let input = '{"key1":"1","key2":"someString"}';
let output = input
  .replace(/"(\w+)":/g, '$1:')
  .replace(/"(\d+)"/g, '$1');
console.log(output);
junvar
  • 11,151
  • 2
  • 30
  • 46
  • I edited my post. I also need the first value to have the quotes removed. This IS correct though for removing quotes from keys. – user1639227 Jan 13 '20 at 21:28
0

Try this:

const
    input = '{"key1":"1","key2":"someString"}',
    output = '{' + Object.entries(JSON.parse(input)).map(([key, value]) => `${key}: ${isNaN(Number(value)) ? `"${value}"` : value}`).join() + '}';
    
console.log(output);
Nave Sade
  • 441
  • 2
  • 6