busyPixels
busyPixels

Reputation: 375

How can I format a string to fix indentation in Javascript?

I am parsing a file in order to make some documentation.

The string I am being returned is:

"([ {
                href: "sass.html",
                text: "Sass"
            }, {
                href: "components.html",
                text: "Components"
            }, {
                href: "javascript.html",
                text: "Javascript"
            } ])
            "

I would like to prettify this so I can output it into a pre tag. So the ideal output would be something like this:

"(
  [
    {
      href: "sass.html",
      text: "Sass"
    },
    {
      href: "components.html",
      text: "Components"
    },
    {
      href: "javascript.html",
      text: "Javascript"
    }
  ]
)"

I am currently thinking I could remove all spacing in the string via:

string.replace(/\s/g,'')

Then do a bunch of splits to break each line apart and add spacing for indentation and rejoin it but this feels messy to me. Is there a better way I could so this?

Any advice is of course greatly appreciated.

This is different from: How can I beautify JSON programmatically? because i am dealing with a string on non-valid JSON.

Upvotes: 0

Views: 1334

Answers (1)

GregL
GregL

Reputation: 38103

The difficulty is that the format you have is strange, it is not valid JSON, so you can't use JSON.parse() directly.

It is not valid JSON for 2 reasons:

  1. It is surrounded by ( and ) for some reason.
  2. The keys are not double-quoted.

So what you ideally need to do is to convert the string into valid JSON first, then try and parse it.

A shortcut, if you are sure you trust this data, is to just get rid of the parentheses first and then use the much-vilified eval(), because it will get around the fact that the keys aren't quoted.

Here is the one-liner for that (assuming the string is in a variable called s):

JSON.stringify(eval(s.substring(s.indexOf('(') + 1, s.lastIndexOf(')'))), null, "\t")

Or to split it out a bit:

var pseudoJson = s.substring(s.indexOf('(') + 1, s.lastIndexOf(')'));
JSON.stringify(eval(pseudoJson), null, "\t");

Upvotes: 1

Related Questions