Tutorial

JSON.parse() および JSON.stringify() の使用方法

Published on December 16, 2020
authorauthor

Alligator.io and Haley Mills

日本語
JSON.parse() および JSON.stringify() の使用方法

はじめに

すべての最新ブラウザで使用可能なJSON オブジェクトには、JSON 形式のコンテンツを処理するための便利なメソッドであるparsestringifyの 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.

Learn more about our products

About the author(s)

Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


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!

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.