Search code examples
javascriptjsonapiresttext

String separated by # and | to json with javascript


I am sorry if this is a newbie question, I am recently started to work with Javascript.

I've got a string that looks like this:

myString = "#101|Maria|Smith|Teacher|26000|Football #102|Albert|Sullivan|Pianist|85000|Swimming"

My desired outcome would be a json like the following:

[
    {
        "id": "101"
        "Name": "Maria",
        "LastName": "Smith"
        "Job": "Teacher",
        "Salary": "26000",
        "FavSport": "Football"
    },
    {
        "id": "102"
        "Name": "Albert",
        "LastName": "Sullivan"
        "Job": "Pianist",
        "Salary": "85000",
        "FavSport": "Swimming"
    }
]

I have tried using myString.split('#') but it returns an array that is still separated by vertical bars and that I am not able to separate. Any ideas are highly appreciated


Solution

  • Split by space " " to get first your groups
    Then, split by pipe "|" to get an array of values
    Then .map() your array to a new Array of objects

    const myString = "#101|Maria|Smith|Teacher|26000|Football #102|Albert|Sullivan|Pianist|85000|Swimming";
    
    const groups = myString.split(" ");
    
    const result = groups.map((groupString) => {
      const [id, Name, LastName, Job, Salary, FavSport] = groupString.split("|");
      return {id: id.replace("#", ""), Name, LastName, Job, Salary, FavSport};
    });
    
    console.log(result)

    Then, to convert it to a JSON String use:

    const json = JSON.stringify(result);
    

    PS: Anyways, I would highly discourage you from using that input string format