-1

I have a strange problem with a string that I am trying to parse as Json. In the database, the json is saved in the following way

 {'Sales Package': '1 Ring, 1 Ring Gift Box, Ring Certificate'}
 typeof = string

When I try to use Object.keys, it won't work because it is seen as a string. If I try to parse it, I get the following error

 {'Sales Package': '1 Ring, 1 Ring Gift Box, Ring Certificate'}
[1]  ^
[1] 
[1] SyntaxError: Expected property name or '}' in JSON at position 1

My code

 metaData.meta_data.attributes.forEach((attribute: string) => {
               console.log(JSON.parse(attribute));
               console.log(attribute);
               //console.log(Object.keys(attribute));
           });

An idea for a solution? I have searched for similar problems but they were of no use to me

Key Lol
  • 75
  • 6
  • 1
    It looks like an object, not a string – Konrad Nov 30 '22 at 18:29
  • 2
    That isn't valid JSON so you _can't_ parse it. JSON requires double-quotes where applicable. – Andy Nov 30 '22 at 18:30
  • For additional reference on double-quoting in JSON: https://stackoverflow.com/questions/949449/do-the-json-keys-have-to-be-surrounded-by-quotes and https://stackoverflow.com/questions/883243/does-json-parse-require-double-quoting – j3py Nov 30 '22 at 18:43

1 Answers1

2

If you must store the single quotes, replace them with double quotes before parsing.

The first replaceALL just replaces any double quotes to " for instances like where a double quote is being used like for inches etc..

The second then replaces single quotes with double quotes.

let str = "{'Sales Package': '1 Ring, 1 Ring Gift Box, Ring Certificate'}";
str = str.replaceAll("\"", """)
str = str.replaceAll("'","\"");

console.log(JSON.parse(str));
imvain2
  • 15,480
  • 1
  • 16
  • 21