0

I am trying to convert CSV to JSON in angularjs, but I am unable to.

Here is the raw data, I receive from API -

"sentby: Sanjay, sitename: Flipkart, PinCode: 080, stdnumber: 56477382, website: https://flipkart.com, status: Done".

I want to convert this to JSON

4
  • is this a string you get or object literals? Commented May 20, 2016 at 16:35
  • Yes it a object literals Commented May 20, 2016 at 16:38
  • @ManishMallavarapu yes I am splitting the string now, but later I realized that ng-model won't work, I am using comma delimiter Commented May 20, 2016 at 16:39
  • let res = {};str.split(', ').forEach(s=>{let t = s.split(': '); res[t[0]] = t[1];}); Commented May 20, 2016 at 16:45

1 Answer 1

4

You could convert a csv string into an object with something like this

var csv = "sentby: Sanjay, sitename: Flipkart, PinCode: 080, stdnumber: 56477382, website: https://flipkart.com, status: Done";
console.log(csv
    .split(',')
    .reduce(function (obj, field) {
        var parts = field.split(':');
        obj[parts[0].trim()] = parts[1].trim();
        return obj;
    }, {}));
Sign up to request clarification or add additional context in comments.

2 Comments

This answer could probably be improved by explaining why it works. Not everyone understands how reduce and similar methods of the Array object work.
This works for the given example, but not all CSVs. The allowance for escaped commas makes it trickier.

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.