Home > Net >  Converting JSON string to JS code snippet
Converting JSON string to JS code snippet

Time:12-10

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 or do I need to write my own boilerplate function to achieve so?

CodePudding user response:

just convert to and from 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"}}}';

let json_object = JSON.parse(json)

CodePudding user response:

You can produce this code with

'let json = '   json   ';'

Example

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"
        }
    }
}`;

console.log('let json = '   json   ';');

  • Related