Javascript object Vs JSON

后端 未结 5 1030
故里飘歌
故里飘歌 2020-11-22 08:04

I want to understand the basic differences clearly between Javascript object and JSON string.

Let\'s say I create the following JS variable:

var test         


        
5条回答
  •  盖世英雄少女心
    2020-11-22 08:21

    Question already has good answers posted, I am adding a small example below, which will make it more easy to understand the explanations given in previous answers. Copy paste below snippet to your IDE for better understanding and comment the line containing invalid_javascript_object_no_quotes object declaration to avoid compile time error.

    // Valid JSON strings(Observe quotes)
    valid_json = '{"key":"value"}'
    valid_json_2 = '{"key 1":"value 1"}' // Observe the space(special character) in key - still valid
    
    
    //Valid Javascript object
    valid_javascript_object_no_quotes = {
        key: "value"  //No special character in key, hence it is valid without quotes for key
    }
    
    
    //Valid Javascript object
    valid_javascript_object_quotes = {
        key:"value",  //No special character in key, hence it is valid without quotes for key
        "key 1": "value 1" // Space (special character) present in key, therefore key must be contained in double quotes  - Valid
    }
    
    
    
    console.log(typeof valid_json) // string
    console.log(typeof valid_javascript_object_no_quotes) // object
    console.log(typeof valid_javascript_object_quotes) // object
    
    //Invalid Javascript object 
    invalid_javascript_object_no_quotes = {
       key 1: "value"//Space (special character) present in key, since key is not enclosed with double quotes "Invalid Javascript Object"
    }
    

提交回复
热议问题