0

I have string like below:

const diaChinh = "{'codeTinh':'HN', 'tinh' : 'Hà Nội' , 'codeHuyen ': 718, 'huyen ': 'Quận Bắc Từ Liêm, Hà Nội'}"

How to format it like below:

const diaChinh = {codeTinh:'HN', tinh : 'Hà Nội' , codeHuyen: 718, huyen: 'Quận Bắc Từ Liêm, Hà Nội'}
AmerllicA
  • 29,059
  • 15
  • 130
  • 154
  • Is this really the way the string is quoted? With single `'` quotes around the properties and values? It's not valid JSON like that. – Mark Oct 07 '18 at 03:05
  • Read here to write down your variable contents: https://stackoverflow.com/questions/10305365/javascript-chrome-how-to-copy-an-object-from-the-webkit-inspector-as-code – protoproto Oct 07 '18 at 03:08

1 Answers1

2

First you have to replace ' inside your JSON with ". Then, you have to remove any kind of whitespace(s) present in property strings like in 'codeHuyen ': 718, 'huyen ': 'Quận Bắc Từ Liêm, Hà Nội'

You can use JSON.parse method.

var diaChinh = "{'codeTinh':'HN', 'tinh' : 'Hà Nội' , 'codeHuyen ': 718, 'huyen ': 'Quận Bắc Từ Liêm, Hà Nội'}";

diaChinh = diaChinh.replace(/\s+(?='\s*:\s*,*)/g, '');
diaChinh = diaChinh.replace(/\'/g, '"');

var obj = JSON.parse(diaChinh);
console.log(obj.huyen);
vrintle
  • 5,501
  • 2
  • 16
  • 46
  • 1
    Hi @ThủyVũVăn if this (or any other further answers) has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this – vrintle Oct 07 '18 at 06:21