Tutorial

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

Published on December 15, 2020
Default avatar

By Alligator.io

日本語
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 us


About the authors
Default avatar
Alligator.io

author



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!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

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

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

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

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel