【保存版】JavaScriptでオブジェクトをJSONに変換する方法と、フォーマットのコツ
JavaScript でオブジェクトから直接フォーマットされた読みやすい JSON を生成する方法
基本的な使用方法
const obj = {
name: "John Doe",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(obj);
console.log(jsonString);
このコードを実行すると、以下の出力が得られます。
{"name":"John Doe","age":30,"city":"New York"}
オプション
JSON.stringify()
関数は、オプション引数を使用して、出力される JSON の書式をさらに制御できます。
- space オプション: 生成された JSON にインデントと改行を追加します。値は、インデントに使用される空白文字の数です。
const jsonString = JSON.stringify(obj, null, 2);
console.log(jsonString);
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
- replacer オプション: オブジェクト内の特定のキーや値をカスタマイズする方法を提供するコールバック関数です。
const jsonString = JSON.stringify(obj, function(key, value) {
if (key === 'age') {
return value - 10;
}
return value;
});
console.log(jsonString);
{"name":"John Doe","age":20,"city":"New York"}
その他のヒント
- オブジェクト内に循環参照がある場合、
JSON.stringify()
関数はエラーをスローします。循環参照を避けるために、循環参照を削除するか、replacer
オプションを使用して循環参照を処理する必要があります。 - オブジェクト内に Date オブジェクトが含まれている場合、
JSON.stringify()
関数はデフォルトで ISO 形式で日付を文字列化します。カスタムの日付書式を使用するには、replacer
オプションを使用する必要があります。
const obj = {
"name": "John Doe",
"age": 30,
"city": "New York",
"friends": [
{ "name": "Jane Doe", "age": 25 },
{ "name": "Peter Jones", "age": 32 }
]
};
const jsonString = JSON.stringify(obj, null, 2);
console.log(jsonString);
This code will output the following JSON:
{
"name": "John Doe",
"age": 30,
"city": "New York",
"friends": [
{
"name": "Jane Doe",
"age": 25
},
{
"name": "Peter Jones",
"age": 32
}
]
}
Let's break down the code:
Call the JSON.stringify() function: The
JSON.stringify()
function takes three arguments:- The object to convert to JSON
- An optional replacer function
- An optional space parameter
In this case, we are only passing in the first argument, which is the object we want to convert to JSON. This will generate a JSON string with no indentation or line breaks.
Here is another example of how to use the JSON.stringify()
function with the replacer
option to customize the output:
const obj = {
"name": "John Doe",
"age": 30,
"city": "New York",
"friends": [
{ "name": "Jane Doe", "age": 25 },
{ "name": "Peter Jones", "age": 32 }
]
};
const replacer = function(key, value) {
if (key === "age") {
return value - 10;
}
return value;
};
const jsonString = JSON.stringify(obj, replacer, 2);
console.log(jsonString);
{
"name": "John Doe",
"age": 20,
"city": "New York",
"friends": [
{
"name": "Jane Doe",
"age": 15
},
{
"name": "Peter Jones",
"age": 22
}
]
}
In this example, the replacer
function is used to modify the value of the age
property for both the object and its friends. This is done by subtracting 10 from the value of the age
property.
I hope this helps!
手動で JSON 文字列を構築する
これは、単純なオブジェクトを JSON に変換する場合に役立つ簡単な方法です。
const obj = {
name: "John Doe",
age: 30,
city: "New York"
};
const jsonString = '{ "name": "' + obj.name + '", "age": ' + obj.age + ', "city": "' + obj.city + '" }';
console.log(jsonString);
{"name":"John Doe","age":30,"city":"New York"}
JSON.parse() 関数と組み合わせて使用する
この方法は、まずオブジェクトを JSON 文字列に変換し、次に JSON.parse()
関数を使用してオブジェクトに戻してから、フォーマットします。
const obj = {
name: "John Doe",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(obj);
const parsedObj = JSON.parse(jsonString);
const formattedJSON = JSON.stringify(parsedObj, null, 2);
console.log(formattedJSON);
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
ライブラリを使用する
json-formatter
や prettyjson
などのライブラリを使用すると、オブジェクトをフォーマットされた JSON に簡単に変換できます。
const obj = {
name: "John Doe",
age: 30,
city: "New York"
};
const { format } = require('json-formatter');
const formattedJSON = format(obj, { indent: 2 });
console.log(formattedJSON);
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
- シンプルで軽量な方法: 手動で JSON 文字列を構築するか、
JSON.parse()
関数と組み合わせて使用します。 - 柔軟性と制御:
JSON.stringify()
関数のオプションを使用して、出力をカスタマイズします。 - 使いやすさ:
json-formatter
やprettyjson
などのライブラリを使用します。
javascript json formatting