AKR
AKR

Reputation: 3

Javascript Convert string in a different format to Json

In Javascript, I've a string that needs to be converted to JSON. I tried converting it with regex as below, but didnot get the expected result:

var testData = "{	name=xyz, \
	ip=[127.0.0.1], \
  machine_id=AVC_ASD_QWESF, \
	sys_Properties=[{ \
				Memory=4 GB, \
				system_type={ \
						OS=64 bit, \
						processor=64 bit \
						} \
				}] \
}";
var testJson = '';
var testArray = testData.split(',');
testArray.forEach(function(item) {
  var kvp = item.split('=');

  if (kvp.length > 1) {
    var key = kvp[0];
    var value = kvp[1];
    var value1 = '';

    if (kvp.length > 2) {
      value1 = kvp[2];

      value1 = value1.replace(/\b[a-zA-Z0-9]/gi, function(char) {
        return '"' + char;
      })
      value1 = value1.replace(/[a-zA-Z0-9]\b/gi, function(char) {
        return char + '"';
      })

      value = value + '": ' + value1;
    } else if (kvp.length = 2) {
      value = value.replace(/\b[a-zA-Z0-9]/gi, function(char) {
        return '"' + char;
      })
      value = value.replace(/[a-zA-Z0-9]\b/gi, function(char) {
        return char + '"';
      })
    }

    key = key.replace(/\b[a-z]/gi, function(char) {
      return '"' + char;
    })

    testJson = testJson + key + '": ' + value + ',';
  } else {
    testJson = testJson + item + ",";
  }
});

Is there any option to include symbols like, '.' to be included in the word boundary.

EDIT:

Expected JSON-format:

{ 
  "name":"xyz", 
  "ip":["127.0.0.1"], 
  "machine_id":"AVC_ASD_QWESF", 
  "sys_Properties":[
      { "Memory":"4 GB", 
          "system_type":{ 
              "OS:64 bit", 
              "processor":"64 bit" 
          } 
       }
  ] 
} 

Upvotes: 0

Views: 85

Answers (2)

Arif Rathod
Arif Rathod

Reputation: 693

try this. i have solved it by using simple one regex.

var testData = '{   name=xyz, \
ip=[127.0.0.1], \
machine_id=AVC_ASD_QWESF, \
sys_Properties=[{ \
            Memory=4 GB, \
            system_type={ \
                    OS=64 bit, \
                    processor=64 bit \
                    } \
            }] \}';

var testJson = testData.replace(/(\s)([^\s]*)(\=)/g,'"$2"$3').replace(/(\=)/g, ":").replace(/\s+/g," ").replace(/(\:)([^\:\,\}]*)(\,|\})/g,'$1"$2"$3').replace(/(\")(\[)(.*)(\])(\")/g,"$2$1$3$5$4");

console.log(JSON.parse(testJson))

Upvotes: 0

wp78de
wp78de

Reputation: 18950

Try it like this with a .replace callback:

const regex = /\s*(\w+)\s*(?==)|(=\[?)([^,{\[\]}\n]+)/g;
const str = `{	name=xyz, 
	ip=[127.0.0.1], 
  machine_id=AVC_ASD_QWESF, 
	sys_Properties=[{ 
				Memory=4 GB, 
				system_type={ 
						OS=64 bit, 
						processor=64 bit 
						} 
				}] 
}`;

const result = str.replace(regex, function(m, group1, group2, group3) {
    if (group1) return `"${group1}"`; //key
    else if (group2) return `${group2}"${group3}"`;   // ="value"
    //else return m;
});
console.log(result.replace(/\=/g,  ':')
                  .replace(/(".+?")|\s+/g,  `$1`)); 
//replace remaining = with colon, and optional: replace remaining whitespace

This could have been very easy without the ip key-value pair. I tried to keep it simple and replaced the remaining = with a colon in a final step. Optionally, we can also remove the remaining whitespace then or use JSON.stringify(JSON.parse(result)).

Upvotes: 1

Related Questions