Home > other >  Filtering an array of JSON objects with strange characters
Filtering an array of JSON objects with strange characters

Time:02-08

Can be safely closed. This is not a valid question anymore.

CodePudding user response:

You should be using JSON.parse() to parse JSON, since body and Message are JSON strings.

const records = [{
    messageId: '1',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm1"\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '2',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm3\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '3',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm8\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
];

let output = [];
let message = [];
output = records.filter((resource) => {
  console.log('resource:', resource);
  const body = resource.body ? JSON.parse(resource.body) : {};
  message = body.message ? JSON.parse(body.Message) : {};
  console.log('message:', message);
  const documentType = message?.detail?.documentType?.toLowerCase() || '';
  console.log('decoumentType:', documentType);
  const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
  return acceptedDocTypes.includes(documentType);
});

CodePudding user response:

If your backslashes are consistent, you can try removing them using a regex:

const records = [
  {
    messageId: '2',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm3\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '3',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm8\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
]

records.forEach(record => record.body = record.body.replace(/(\\ ")/gmi, '"'))

records.forEach(record => record.body = record.body.replace(/\s*"\s*\{/gmi, '{').replace(/\s*\}\s*"/gmi, '}'))

records.forEach(record => record.body = JSON.parse(record.body))

console.log(records)

In this way, you first clean the input, then you can apply JSON.parse. This doesn't work with your first example since there's an extra unescaped quote, but I suppose it was a typo in your writing.

  •  Tags:  
  • Related