LoginSignup
15
22

More than 3 years have passed since last update.

JSONとは(JavaScriptとJSONの違い)

Last updated at Posted at 2020-09-02

JSONって結局なんなんだ?っと思っていろいろ調べたのでまとめる

JSONとは

  • JSONはJavaScriptオブジェクトの表記法をベースにした"データフォーマット"
  • JSON自体は文字列でもオブジェクトでもなく、ただの”データフォーマット”
  • JavaScript言語の元に、JS形式のオブジェクト(JSオブジェクト)、JS形式の文字列(JS文字列)などが存在するのと同様に、 JSONというデータ定義言語の元に、JSON形式のオブジェクト(JSONオブジェクト)、JSON形式の文字列(JSON文字列)が存在する

以下でJSONオブジェクト、JSON文字列、それらへの変換方法を記述する。

JSONオブジェクト

  • キー(プロパティ名)はダブルクォートで囲んだ文字列でないといけない
  • オブジェクトの末尾にカンマ置いてはいけない
// ***JSONオブジェクト***
let JSON_Object = {
    "place": "Osaka",
    "number": 2
}
console.log(JSON_Object.place); //JSオブジェクト同様キーを指定して値を参照できる

// ***JSオブジェクト***
let JS_Object = {
    place: "Osaka",
    number: 2, //←末尾カンマはつけてもOK
}

JSON文字列

  • 定義的にはJS文字列と同じ
  • 一般的にJSONオブジェクトを文字列にしたものを指すことが多い
  • 文字列なのでキーを指定して値を参照できない
// ***JSON文字列***
let JSON_Str = '{"place": "Osaka","number": 2}'
console.log(JSON_Str.place); //errになる → キーを指定して値を参照できない

JSON.stringify()

JavaScript のオブジェクトや値をJSON文字列に変換するメソッド
JSオブジェクトに関してはJSONオブジェクトの文字列に変換される

// ***JSオブジェクトを変換**
let JS_Object = {
    place: "Osaka",
    number: 2,
}
console.log(JSON.stringify(JSON_Object));
//出力  :  {"place":"Osaka","number":2}


// *** JSリスト,JS数値を変換
console.log(JSON.stringify([1, 2, 3]));
// 出力  :  "[1,2,3]"
console.log(JSON.stringify(1000));
// 出力  :  "1000"

JSON.parse()

文字列をJSONとして解析してJavaScriptのオブジェクトや値に変換するメソッド
JSON.stringify()の逆

console.log(JSON.parse('{"place": "Osaka","number": 2}'));
//出力 { place: 'Osaka', number: 2 }
console.log(JSON.parse("[1,2,3]"));
// 出力 [ 1, 2, 3 ]
console.log(JSON.parse("1"));
// 出力 1

参考リンク

15
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
22