Skip to main content

JSON Examples

Example1: 

var jsonNum = "{\"items\": [\"1\",\"2\",\"3\"]}";
var jsonString = "{\"items\" : [\"first\",\"begin \",\" test \",\"best\",\"last\",\"end\"] } " 

              var jsobj = Ext.JSON.decode(jsonString);
              console.log(jsobj.items[0]);  // returns array obj
                                    var recs = jsobj.items;
              
              var jsObject = JSON.parse(jsonNum); 
              console.log(jsObject.items[1]);


Example2:


var obj1 = {user:"John",age:22,country:"USA"};
var obj2 = {user:"Will",age:27,country:"UK"};
var obj3 = {user:"Abiel",age:19,country:"Mexico"};
var obj4 = {u1:obj1, u2:obj2, u3:obj3};
document.write(obj1.user);
document.write("
");
document.write(obj3.user+"is "+obj3.age+ " yrs old lives in"+ obj3.country);
obj3.country = "Italy";
document.write("
");
document.write(obj3.user+" lives in "+ obj3.country);
document.write("
");
document.writeln(obj4.u2.country); //UK
document.write("
");
document.writeln(obj4["u2"]["user"]);

var meats = ["beef","pork","lamb","fish"];
var fruit = ["apple","plumb","grape","orange" ];
var obj5 = { arr1:meats,arr2:fruit };
document.writeln(obj5.arr1[1]);
document.write("
");
document.write(obj5.arr2[3]);
document.write("
");

var jsonStr = 
{
    "name": "Product",
    "properties": {
        "id": {
            "type": "number",
            "description": "Product identifier",
            "required": true
        },
        "name": {
            "type": "string",
            "description": "Name of the product",
            "required": true
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "required": true
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "stock": {
            "type": "object",
            "properties": {
                "warehouse": {
                    "type": "number"
                },
                "retail": {
                    "type": "number"
                }
            }
        }
    }
};
document.write("Nested object: "+jsonStr.properties.id.description);
document.write("
");
var myObject = {
  "first": "John",
  "last": "Doe",
  "age": 39,
  "sex": "M",
  "salary": 70000,
  "registered": true,
  "interests": [ "Reading", "Mountain Biking", "Hacking" ],
  "favorites": {
    "color": "Blue",
    "sport": "Soccer",
    "food": "Spaghetti"
  }, 
  "skills": [
    {
      "category": "JavaScript",
      "tests": [
        { "name": "One", "score": 90 },
        { "name": "Two", "score": 96 }
      ] 
    },
    {
      "category": "CouchDB",
      "tests": [
        { "name": "One", "score": 79 },
        { "name": "Two", "score": 84 }
      ] 
    },
    {
      "category": "Node.js",
      "tests": [
        { "name": "One", "score": 97 },
        { "name": "Two", "score": 93 }
      ] 
    }
  ]
};
document.writeln(myObject.skills[0].category);
document.write("
");
document.writeln(myObject["skills"][0]["category"]);
document.write("
");
document.writeln(myObject.skills[1].tests[0].score); 
document.writeln(myObject["skills"][1]["tests"][0]["score"]);



Example 3:
// php:
/*
header("Content-Type: application/json"); //set the content type to xml

$jsonData = ' {
"u1": { "user":"John","age":22,"country":"United States"},
"u2": { "user":"Will","age":27,"country":"United Kingdom"},
"u3": { "user":"Raja","age":19,"country":"India"},
"u4": { "user":"Rick","age":19,"country":"Mexico"}
}';
echo $jsonData;
?>
*/

// javascript
function ajax_get_json(){
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest(); 
    hr.open("GET", "my_json_list.php", true); // use json data 
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/json");
    // Access the onreadystatechange event for the XMLHttpRequest object
   hr.onreadystatechange = function() {
   if(hr.readyState == 4 && hr.status == 200) {
   var data = JSON.parse(hr.responseText);
  var results = document.getElementById("results");
document.getElementById("users").innerHTML = data.u3.user;
//results.innerHTML = data.u2.user+" is "+data.u2.age+ " yrs old lives in "+ data.u2.country;
results.innerHTML = "";
for(var obj in data){  // loop complete json object
results.innerHTML += data[obj].user+" is "+data[obj].age+ " yrs and lives in "+ data[obj].country+"
" ;
 }
    }
    }
    
hr.send(null);  //use json data
    results.innerHTML = "requesting..."; // can use img tag, animated gif file
}




Comments

  1. I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in Couch DB, kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor led training on Couch DB. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
    For Demo Contact us.
    Nitesh Kumar
    MaxMunus
    E-mail: nitesh@maxmunus.com
    Skype id: nitesh_maxmunus
    Ph:(+91) 8553912023
    http://www.maxmunus.com/




    ReplyDelete

Post a Comment

Popular posts from this blog

ExtJS - Grid panel features

What can we do with ExtJS GridPanel? I have to develop a lot of applications in my web app and I see that grid component of ExtJS may fit in. However, I am not aware of what all things I can do with the - off the shelf available framework pieces - available plug-ins in the marketplace and - custom development through my own developers This is a typical question that we hear from the business users who wants to design an application by keeping the framework’s capability in perspective. In this article I have tried to put the list of stuff you can do with grid and hopefully that shall enable you to take advantage of the beauty of ExtJS. Pre-requisites This article assumes that you are familiar with basics of ExtJS What are the available options? In this section I will be taking you through some of the commonly seen usage of ExtJS grid panel. While covering all the capabilities of grid may not be possible, I am sure it will be helpful for the business users who want to...

ExtJS 4 with Spring MVC Example

Introduction When developing a brand new application for the company I work for, one of the first thing I implement is "authentication". Not only is this process generally a prerequisite to access many other functions but it is also very simple and covers every layer of an application, from GUI to the database. So instead of another minimalistic "Hello World" tutorial, here is a "Login/Password" example, using 2 famous technologies : Spring MVC and ExtJS 4.   Prerequisites Because this tutorial is quite long, I won't go into the details of each technology I used but I will mainly focus on how ExtJS and Spring can be nicely used together. So here are the things you should know before continuing : Spring framework (good knowledge) Spring MVC (basic knowledge. See  Spring MVC Official Documentation  for details) ExtJS "application architecture" (see  Sencha Docs  for details) Eclipse IDE + Tomcat 6 (or any other web container) You a...

Ext4 Apply Store Filtering

In extjs4.1: There are many way for store filtering . Some of code i give here Filtering by single field: store . filter ( 'eyeColor' , 'Brown' );   Alternatively, if filters are configured with an  id , then existing filters store may be  replaced by new filters having the same  id . Filtering by single field: store . filter ( "email" , /\.com$/ );   Using multiple filters: store . filter ([ { property : "email" , value : /\.com$/ }, { filterFn : function ( item ) { return item . get ( "age" ) > 10 ; }} ]);   Using  Ext.util.Filter  instances instead of config objects (note that we need to specify the root config option in this case): store . filter ([ Ext . create ( ' Ext.util.Filter ' , {   property : "email" , value : /\.com$/ , root : 'data' }),   Ext . create ( ' Ext.util.Filter ' , {   filterFn : function ( item ) {   return item . get ( ...