0

I have a string that looks like:

var str = '{ "abc": {
            "decline_reason": "Business rule switched off"
        },
        "def": {
            "decline_reason": "No response by interface"
        },
        "ghi": {
            "decline_reason": "Requested incorrect size" }';

I would like to split that string into an array that I can use to populate a table on a webpage. I intend to use the initial reference ('abc'), with the reason ('Business rule switched off') on row 1, initial reference ('def'), with the reason ('No response by interface') on row 2, etc...

I have tried regex to break it down, and I've managed to find one that removes quotes, but not to break the string down.

I intend to populate the table with code like:

<table id="declinesTable">
            <tr>
                <th onclick="sortTable(0)">Reference Code</th>
                <th>Decline Reason</th>
            </tr>
            <tr id="lender1">
                <td id="lender1"><script>document.getElementById("lender1").innerHTML = declines[0];</script>
                </td>
                <td id="declineReason1"><script>document.getElementById("declineReason1").innerHTML = declines[2];</script>
                </td>
            </tr>
        </table>

skipping out the value "decline_reason" from the table.

Any suggestions?

2
  • Your string is in JSON format; rather than trying to tackle it with regex I'd strongly suggest JSON.parse() to convert it into an object Commented Feb 19, 2021 at 14:41
  • On closer look, it's almost in JSON format; it's malformed (missing a trailing }) Commented Feb 19, 2021 at 14:44

1 Answer 1

2

Couple of things - your string is missing a final }. Not sure where you're getting the string from, but it's in JSON format, so use JSON.parse to get it into an object, then iterate over the object to do something with each individual nested object. I would strongly recommend using a library like jQuery to help you append it to the table. You can google and very quickly find out how to add jQuery to your project. See below.

function stringParse(str) {
  const json = JSON.parse(str);
  const html = Object.entries(json).reduce((h, [k, v]) => 
    h += `<tr><td>${k}</td><td>${v.decline_reason}</td></tr>`
  , "");

  $('#declinesTable').append(html);
}


const str = '{ "abc": {"decline_reason": "Business rule switched off"},"def": {"decline_reason": "No response by interface"},"ghi": {"decline_reason": "Requested incorrect size"}}'
stringParse(str);
<table id="declinesTable">
  <tr>
    <th>Reference Code</th>
    <th>Decline Reason</th>
  </tr>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

13
  • Spot on. Avoid keeping data as raw string as much as possible. As soon as the data enters your system you should be trying to unmarshall it to something.
    – Dropout
    Commented Feb 19, 2021 at 14:52
  • Again and again:learn.jquery.com/performance/append-outside-loop Commented Feb 19, 2021 at 15:01
  • Did not know this. I'll edit my answer. Thanks. Commented Feb 19, 2021 at 15:02
  • @kdsprogrammer also Object.entries(items).forEach(([k, v]) => {}) or rather use .reduce() like: const TRs = Object.entries(items).reduce((h, [k, v]) => { h += `<tr><td>${k}</td><td>${v}</td></tr>`;}, ""); and than just: $('#declinesTable').append(TRs); Commented Feb 19, 2021 at 15:03
  • That output when I run the code snippet is absolutely perfect!! when I've put the code directly onto the page, I'm seeing an error of "Uncaught referenceError: $ is not defined", and that is referring to the line with the 'append(html);' on it. I'm not sure what that refers to as I literally copy/pasted, so that I can try it
    – Steve_G
    Commented Feb 19, 2021 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.