假設我們有一個 JSON 字串:
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"
}
}
}`;
我可以決議它使用 JSON.parse(json)
但是如果我想從這樣的字串創建它的 js 代碼片段怎么辦:
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"
}
}
};
是否有任何可用的庫,或者我是否需要撰寫自己的樣板函式來實作?
uj5u.com熱心網友回復:
只需與 json 字串相互轉換即可。
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)
uj5u.com熱心網友回復:
您可以使用以下代碼生成此代碼
'let json = ' json ';'
例子
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 ';');
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/378783.html
標籤:javascript json
