By Alligator and Haley Mills
すべての最新ブラウザで使用可能なJSON
オブジェクトには、JSON 形式のコンテンツを処理するための便利なメソッドであるparse
とstringify
の 2 種類があります。JSON.parse()
は、JSON 文字列を取得し、JavaScriptオブジェクトに変換します。JSON.stringify()
は、JavaScriptオブジェクトを取得し、JSON 文字列に変換します。
次に例を示します。
const myObj = {
name: 'Skip',
age: 2,
favoriteFood: 'Steak'
};
const myObjStr = JSON.stringify(myObj);
console.log(myObjStr);
// "{"name":"Sammy","age":6,"favoriteFood":"Tofu"}"
console.log(JSON.parse(myObjStr));
// Object {name:"Sammy",age:6,favoriteFood:"Tofu"}
また、メソッドは通常オブジェクトで使用されますが、配列でも使用できます。
const myArr = ['bacon', 'lettuce', 'tomatoes'];
const myArrStr = JSON.stringify(myArr);
console.log(myArrStr);
// "["shark","fish","dolphin"]"
console.log(JSON.parse(myArrStr));
// ["shark","fish","dolphin"]
JSON.parse()
JSON.parse()
は、値が返される前にオブジェクト値を変換できる2つ目の引数として、関数を指定することができます。この時、parse
メソッドの返されたオブジェクトでは、オブジェクトの値が大文字に変換されます。
const user = {
name: 'Sammy',
email: 'Sammy@domain.com',
plan: 'Pro'
};
const userStr = JSON.stringify(user);
JSON.parse(userStr, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
注: JSON では末尾のカンマは無効なため、渡された文字列の末尾にカンマがある場合、JSON.parse()
は、エラーを表示します。
JSON.stringify()
JSON.stringify()
は、2つの追加引数を指定することができます。1つ目はreplacer
関数で、2 つ目は文字列
または数値
を、返された文字列のスペース(インデント)
として使用します。
replacer 関数を使用すると、 undefined
として返された値が結果の文字列から除外されるため、値をフィルターで除外できます。
const user = {
id: 229,
name: 'Sammy',
email: 'Sammy@domain.com'
};
function replacer(key, value) {
console.log(typeof value);
if (key === 'email') {
return undefined;
}
return value;
}
const userStr = JSON.stringify(user, replacer);
// "{"id":229,"name":"Sammy"}"
そして、スペース
引数が渡された例を示します。
const user = {
name: 'Sammy',
email: 'Sammy@domain.com',
plan: 'Pro'
};
const userStr = JSON.stringify(user, null, '...');
// "{
// ..."name": "Sammy",
// ..."email": "Sammy@domain.com",
// ..."plan": "Pro"
// }"
このチュートリアルでは、JSON.parse()
とJSON.stringify()
メソッドの使用方法を見てきました。JavaScript でJSON を使用する方法について詳しく知りたい場合は、JavaScript でJSON を使用する方法のチュートリアルをご覧ください。
JavaScript でのコーディングの詳細については、JavaScript でのコーディング方法シリーズを参照するか、JavaScriptのトピックページで演習とプログラミングプロジェクトをご覧ください。
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Alligator.io is a developer-focused resource that offers tutorials and insights on a wide range of modern front-end technologies, including Angular 2+, Vue.js, React, TypeScript, Ionic, and JavaScript.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.