0
votes

This is in response to a question asked by a user on this platform. I found it interesting and was trying to find a solution to it. Unfortunately by the time I found one, the question got deleted.

https://stackguides.com/questions/66041498/how-to-transform-api-response-from-into-proper-array-of-object

The user wanted to remove "_text" from the json object. The json looks like below -

{
    type: {
      _text: "user",
    },
    data: {
      desc: {
        _text: "abbc",
      },
      desc1: {
        _text: "jhd",
      },
    },
    data1: {
      clients: {
        client: [
          {
            clientName: {
              _text: "Test 111",
            },
            date: {
              _text: "02/02/2020",
            },
          },
        ],
      },
    },
    msg: {},
    id: {
      _text: "123",
    },
  },
  {
    type: {
      _text: "student",
    },
    data: {
      desc: {
        _text: "dgfg",
      },
      desc1: {
        _text: "jgjg",
      },
    },
    data1: {
      clients: {
        client: [
          {
            clientName: {
              _text: "Test 333",
            },
            date: {
              _text: "02/02/2020",
            },
          },
        ],
      },
    },
    msg: {},
    id: {
      _text: "134",
    },
  },
1

1 Answers

0
votes

Here is a regex that kind of solves the issue.

var str = <the-json-in-questions>;

str.replace(/({\n.*_text: (".*")\1,\n.*})/gi, $2);

I just wanted to thank the author, if he ever comes across this question, that I was able to learn regex backreferencing due to his question.

The final json looks like this -

{
    type: "user",
    data: {
      desc: "abbc",
      desc1: "jhd",
    },
    data1: {
      clients: {
        client: [
          {
            clientName: "Test 111",
            date: "02/02/2020",
          },
        ],
      },
    },
    msg: {},
    id: "123",
  },
  {
    type: "student",
    data: {
      desc: "dgfg",
      desc1: "jgjg",
    },
    data1: {
      clients: {
        client: [
          {
            clientName: "Test 333",
            date: "02/02/2020",
          },
        ],
      },
    },
    msg: {},
    id: "134",
  },

Thanks :D