0

If I have the string

PercentageValue = 99.9,\r\nCaseID = 9745683 PercentageValue = 90.3,\r\nCaseID = 9387593 PercentageValue = 88.6,\r\nCaseID = 4893448

How can I parse it into:

[
    {PercentageValue : '99.9', CaseID : '9745683'},
    {PercentageValue : '90.3', CaseID : '9387593'},
    {PercentageValue : '88.6', CaseID : '4893448'}
]

There seems to be a space delimiter, but the issue is there are other spaces too.

Thanks

2
  • The JSON format you want to achieve is not correct. Maybe you would like : instead of = ? Commented May 28, 2017 at 19:34
  • thanks, fixed typo. Commented May 28, 2017 at 19:35

4 Answers 4

1

var str = 'PercentageValue = 99.9,\r\nCaseID = 9745683 PercentageValue = 90.3,\r\nCaseID = 9387593 PercentageValue = 88.6,\r\nCaseID = 4893448';
var array = str.replace(/\r\n/g, '').replace(/\s=\s/g, ':').split(' ');
var objs = array.map((el) => {
  return {
  	[el.split(',')[0].split(':')[0]]: el.split(',')[0].split(':')[1],
  	[el.split(',')[1].split(':')[0]]: el.split(',')[1].split(':')[1] 	
  }
});
console.log(objs);

Sign up to request clarification or add additional context in comments.

Comments

1

var str = "PercentageValue = 99.9,\r\nCaseID = 9745683 PercentageValue = 90.3,\r\nCaseID = 9387593 PercentageValue = 88.6,\r\nCaseID = 4893448";
var parse = "["+str.replace(/(\w+)\s=\s(\d+(\.\d)?),\r\n(\w+)\s=\s(\d+)/g, "{\"$1\":\"$2\",\"$4\":$5}").replace(/\}\s\{/g, "},{")+"]";
console.log(JSON.parse(parse));

Comments

0
var input = "PercentageValue = 99.9,\r\nCaseID = 9745683 PercentageValue = 90.3,\r\nCaseID = 9387593 PercentageValue = 88.6,\r\nCaseID = 4893448";
var res, resArray = [], re = /PercentageValue = (.*),\r\nCaseID = (\d*) ?/g; 
while (res = re.exec(input)) 
   resArray.push({PercentageValue: res[1], CaseID: res[2]})

Comments

0

As shown by other answers, there are several ways to solve this. Here is an approach with .reduce():

var str = 'PercentageValue = 99.9,\r\nCaseID = 9745683 ' +     
          'PercentageValue = 90.3,\r\nCaseID = 9387593 ' +
          'PercentageValue = 88.6,\r\nCaseID = 4893448';

console.log(
  str
    .split(/ = |,?\s+/)
    .reduce(
      function(c, v, i, a){
        return i & 3 == 3 && (c[i >> 2] = {
          PercentageValue: a[i - 2], 
          CaseID: v
        }), c
      }, []
    )
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.