0

Lets say we have a JSON string :

let json = `{
    "book": {
        "name": "Harry Potter and the Goblet of Fire",
        "author": "J. K. Rowling",
        "year": 2000,
        "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
        "genre": "Fantasy Fiction",
        "price": {
            "paperback": "$10.40", "hardcover": "$20.32", "kindle": "$4.11"
        }
    }
}`;

I can parse it using JSON.parse(json)

But what if I want to create its js code snippet from string like this :

  let json = {
    book: {
      name: "Harry Potter and the Goblet of Fire",
      author: "J. K. Rowling",
      year: 2000,
      characters: ["Harry Potter", "Hermione Granger", "Ron Weasley"],
      genre: "Fantasy Fiction",
      price: {
        paperback: "$10.40",
        hardcover: "$20.32",
        kindle: "$4.11"
      }
    }
  };

Is there any library available for it?

Crossposted from this Stack Overflow question to ask for a library rather than a custom implementation.

1 Answer 1

1

You can use JSON5:

let json = JSON5.stringify(JSON.parse(`{
    "book": {
        "name": "Harry Potter and the Goblet of Fire",
        "author": "J. K. Rowling",
        "year": 2000,
        "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
        "genre": "Fantasy Fiction",
        "price": {
            "paperback": "$10.40", "hardcover": "$20.32", "kindle": "$4.11"
        }
    }
}`), { space: 2 });

console.log('let json = ' + json + ';');
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/index.min.js"></script>

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.