2

How to convert string to valid json ?

const string = "[{foo:bar,key:value},{foo:bar,key:value}]";

So that i can parse it using JSON.parse(string). Note that : i cant manually put (") to every keys and values. I am stack here that's why i am on stackoverflow.

fooo
  • 53
  • 3
  • 3
    Where does this come from to begin with? What's producing not-valid-JSON-JSON? – deceze Aug 09 '19 at 11:28
  • Also, how literally are we to take this sample? Even the `value` is missing quotes…?! – deceze Aug 09 '19 at 11:28
  • is there any way to dynamically add (") on every key and values. because i am getting it from mysql row. – fooo Aug 09 '19 at 11:31
  • 2
    @fooo: You should correct the source of the issue. The place where it gets put wrong into mysql for instance. – Lain Aug 09 '19 at 11:33
  • @Lain you cant insert with the same manner i mean sql command do not allows to insert with ("). take a look here const post = 'insert into post values("Test","[{foo:bar,key:value},{foo:bar,key:value}]")' – fooo Aug 09 '19 at 11:40
  • Possible duplicate of [Parse JSON in JavaScript?](https://stackoverflow.com/questions/4935632/parse-json-in-javascript) – Andrew F Aug 09 '19 at 11:47
  • 1
    Uhm… you're saying there is absolutely no way to insert a string with quotes into an SQL database? None whatsoever?! What if I told you all these messages on this page are stored in SQL somewhere on the backend…? If this is seriously the reason for you needing this hackaround, you seriously need to reevaluate your situation from scratch. – deceze Aug 09 '19 at 11:47
  • i am using mysql 5.1.2 that does not support json data types. @deceze – fooo Aug 09 '19 at 11:50
  • 1
    @fooo maybe it does not support JSON data types but it supports strings – kevinSpaceyIsKeyserSöze Aug 09 '19 at 11:51
  • 1
    …strings *with quotes*… – deceze Aug 09 '19 at 12:04
  • 1
    @fooo: I dunno man, the official manual of MySQL 5.1 kind of contradicts you on this: http://download.nust.na/pub6/mysql/doc/refman/5.1/en/string-syntax.html This should be your command according to the link: `insert into post values("Test","[{\"foo\":\"bar\",\"key\":\"value\"},{\"foo\":\"bar\",\"key\":\"value\"}]")` – Lain Aug 09 '19 at 13:43

1 Answers1

3

Using regex to replace any words or numbers will work for the json you have supplied, it will not however work if you have mixed value and "value" properties.

var text = "[{foo:bar,key:value},{foo:bar,key:value}]";

console.log(JSON.parse(text.replace(/(\w+|\d+)+/g, '"$1"')));
nick zoum
  • 7,216
  • 7
  • 36
  • 80