0

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.

Community
  • 1
  • 1
busyPixels
  • 366
  • 1
  • 5
  • 18
  • 1
    Where is this formatting occurring? Does the object truly need to be indented? – Anthony Forloney Mar 23 '15 at 22:52
  • @gon250 no it isn't. – TheHippo Mar 24 '15 at 04:37
  • @TheHippo: Apparently whoever stole the accepted answer to that question thought so too. Generally, if someone plagiarizes an accepted answer to an existing question, there is a very high chance the question being answered is a duplicate. It's clear that this is an exception to the rule however. – BoltClock Mar 24 '15 at 15:11

1 Answers1

1

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");
GregL
  • 37,147
  • 8
  • 62
  • 67
  • Thanks for this it is almost perfect... the only issue is you are doing: eval(s) instead of eval(pseudoJson). I fixed that and it works great! Thanks again. If you fix that issue I will accept this as the correct answer. – busyPixels Mar 23 '15 at 23:34
  • @busyPixels Good spot. Fixed. – GregL Mar 23 '15 at 23:36