skip to Main Content

I have created simple application in Reactjs, I want to parse JSON array values and remove all slash() could you please help me

const jsonObject = {
  "account_create_view": [
    {
      "accounts": "[2092]",
      "fields_to_display": "["account_name", "company"]",
      "filter_fields": "[{"input": "account_name", "operator": "equals", "values": ["Prakruthi Resources - Saii Resources"]}]",
      "id": 184,
      "unique_name": "acc_12_18",
      "view_name": " acc_12_18"
    }
  ]
};

// Convert the JSON object to a string, remove all backslashes, and parse it back to an object
const cleanedJsonString = JSON.stringify(jsonObject).replace(/\/g, '');
const cleanedObject = JSON.parse(cleanedJsonString);

console.log(cleanedObject);

2

Answers


  1. The reason for this error is in the fields_to_display key there is "[ and ]", which is not removed by your regex.

    const jsonObject = {
      "account_create_view": [
        {
          "accounts": "[2092]",
          "fields_to_display": "["account_name", "company"]",
          "filter_fields": "[{"input": "account_name", "operator": "equals", "values": ["Prakruthi Resources - Saii Resources"]}]",
          "id": 184,
          "unique_name": "acc_12_18",
          "view_name": " acc_12_18"
        }
      ]
    };
    
    const cleanedJsonString = JSON.stringify(jsonObject)
      .replace(/\/g, '')
      .replace(/"[/g, '[')
      .replace(/]"/g, ']');
    const cleanedObject = JSON.parse(cleanedJsonString);
    
    console.log(cleanedObject);
    Login or Signup to reply.
  2. Its because of the nested double quotes, eg: "["account_name", "company"]"

    When you remove the , the double quotes inside are not being changed to single quotes and are not being removed, so you see that error. I would say changed the nested quotes to single quotes or let them be, those only represent presence of quotes inside a string, in the frontend or in the output you do not see them. So, its okay to have them.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search