working on it ...

Filters

Explore Public Snippets

Sort by

Found 42k snippets matching: json

    public by zer00ne  230363  1  6  1

    DB(store, schema) | Store Data in localStorage

    [FORK][ https://www.snip2code.com/Snippet/217248/object-data-store-----stuff-it-in-yer-cl
      // Local Data
       
    function DB(store, schema) {
          this.store = store;
          if (!localStorage[store] || typeof localStorage[store] == 'undefined') {
              localStorage[store] = JSON.stringify(schema|| {});
          }
          this.setData = function (key, val) {
              var lda = JSON.parse(localStorage[this.store]);
              doUpdate(ldta, key, val);
              localStorage[store] = JSON.stringify(ldta);
          };
          this.getData = function (key) {
              var ldta = JSON.parse(localStorage[this.store]);
              if (key) {
                  return pathGet(ldta, key);
              }
              return ldta;
          };
          this.reset = function (schema) {
              localStorage[this.store] = JSON.stringify(schema || {});
          };
          this.delete = function() {
              localStorage.removeItem(this.store);
          };
          var doUpdate = function (ob, kStr, val) {
              var kpth = keyStr.split('.'),
              i = 0, lstIdx = kpth.length - 1;
              for (;i < lstIdx; ++i) {
                  var key = kpth[i];
                  if (!(key in ob)) {
                      ob[key] = {};
                  }
                  ob = ob[key];
              }
              ob[kpth[lstIdx]] = val;
          };
          var pathGet = function (obj, key, leftOvrs) {
              if ( leftOvrs === undefined ) {
                  leftOvrs = key.split('.');
              }
              var cur = leftOvrs.shift();
              if ( typeof(obj) == 'object' && obj[cur] !== undefined ) {
                  if ( leftOvrs.length === 0 ) {
                      return obj[cur];
                  }
                  else if ( typeof(obj[cur]) == 'object' ) {
                      return arguments.callee(obj[cur], undefined, leftOvrs);
                  }
              }
              return null;
          };
      }
                            

    public by Fabax  153781  0  4  0

    turn string into json p

    turn string into json p: echo Json
    function echoJSON($data) {
      $json = json_encode($data);
    	echo isset($_GET['callback'])
    		? "{$_GET['callback']}($json)"
    		: $json;	
    }
    
    

    public by lbottaro  9666  25  8  0

    How to parse the JSON result of a jenkins job in python

    This snippet shows how to get and parse the JSON format of the last execution of a Jenkins job. You have to specify: Jenkins_server - The Jenkins server name/IP address http_port - The port used by Jenkins server job_name - The job name
    import urllib2
    import json 
    
    jenkins_job_dir="http://<Jenkins_server>:<http_port>/view/All/job/<job_name>/lastBuild/api/json"
    def getBuildResult():
        try:      
            jenkinsStream    = urllib2.urlopen(jenkins_job_dir)
    
        except urllib2.HTTPError, e:
            print "URL Error: " + str(e.code) 
            return "FAILURE"
        
        try:
            buildStatusJson = json.load( jenkinsStream )
        except:
            print "Failed to parse json"
            return "FAILURE"
    
        if buildStatusJson.has_key( "result" ):      
            print "build status job " + buildStatusJson["result"]
            if buildStatusJson["result"] != "SUCCESS" :
                return "FAILURE"
        else:
            return "FAILURE"
        return "SUCCESS"
    
    print "loading"
    getBuildResult()
    print "Done"

    public by CodeProjectG  6102  27  6  0

    Nested Json Sample

    {"widget": {
        "debug": "on",
        "window": {
            "title": "Sample Konfabulator Widget",
            "name": "main_window",
            "width": 500,
            "height": 500
        },
        "image": { 
            "src": "Images/Sun.png",
            "name": "sun1",
            "hOffset": 250,
            "vOffset": 250,
            "alignment": "center"
        },
        "text": {
            "data": "Click Here",
            "size": 36,
            "style": "bold",
            "name": "text1",
            "hOffset": 250,
            "vOffset": 100,
            "alignment": "center",
            "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
        }
    }}    

    public by sTiLL-iLL @ SniPitz-KND  4511  2  7  10

    PROMISE! X(ml) 2 J(son)!

    makE XML PROMISE to be JSON DEFERRED....
    var xp = (function(){
       var Promise = function () {
      		return {
      			status: 'pending',error: null,
      			posCBKs: [],negCBKs: [],
      			then: function (posCBK, negCBK) {
      				var defer = new Deferred();
      				posCBK=(!posCBK)?function(d){d=(d||true);return d;}:posCBK;
      				negCBK=(!negCBK)?function(d){d=(d||true);return d;}:negCBK;
      				this.posCBKs.push({
      					func: posCBK,
      					deferred: defer
      				});				
      				this.negCBKs.push({
      					func: negCBK,
      					deferred: defer
      				});
      				if (status == 'resolved') {
      					this.execAction({
      						func: posCBK,
      						deferred: defer
      					}, this.data);
      				} else if (status == 'rejected') {
    					this.execAction({
      						func: negCBK,
      						deferred: defer
      					}, this.error);
      				}
      				return defer.promise;
      			},
      			execAction: function (callbackData, result) {
      				setTimeout(function () {
      					var res = callbackData.func(result);
      					if (res instanceof Promise) {
      						callbackData.deferred.bind(res);
      					} else {
      						callbackData.deferred.resolve(res);
      					}
      				}, 0);
      			}
      		};
      	},
        Deferred=function () {
      	  return {
      	  	promise: new Promise(),
      		  resolve: function (data) {
      			  var pms = this.promise;
      			  pms.data = data;
      			  pms.status = 'resolved';
      		  	if (pms.posCBKs) {
      			  	pms.posCBKs.forEach(function (dta) {
      					pms.execAction(dta, data);
      				});
      			}
      		},
      		reject: function (err) {
      			var pms = this.promise;
      			pms.error = err;
      			pms.status = 'rejected';
      			if (pms.negCBks) {
      				pms.negCBKs.forEach(function (dta) {
      					pms.execAction(dta, err);
      				});
      			}
      		},
      		bind: function (promise) {
      			var slf = this;
      			promise.then(function (dta) {
      				slf.resolve(dta);
      			}, function (err) {
      				slf.reject(err);
      			});
      		}
      	};
      }; // XML to JSON module 
      var xj = function(xml) {
        	var i=0,xJsn={},len={};
        	if (xml.nodeType == 1) {
        		if (xml.attributes.length > 0) {
        		  len = xml.attributes.length;
        		  xJsn["@attributes"] = {};
        			for (;;++i<len) {
        				var xAItm = xml.attributes.item(i);
        				xJsn["@attributes"][xAItm.nodeName] = xAItm.nodeValue;
        			}
        		}
        	}
        	else if(xml.nodeType == 3) {
        		xJsn = xml.nodeValue;
        	}
        	if (xml.childNodes) {
        	  i=0,len=xml.childNodes.length;
        		for(;;++i<len) {
        			var xnd = xml.childNodes.item(i),
        			    xndNm = xnd.nodeName;
        			if (!xJsn[xndNm]) {
        				xJsn[xndNm] = xmlToJson(xnd);
        			} else {
        				if (!xJsn[xndNm].push) {
        					var orig=xJsn[xndNm];
        					xJsn[xndNm]=[];
        					xJsn[xndNm].push(orig);
        				}
        				xJsn[xndNm].push(X2J(xnd));
        			}
        		}
        	}
        	return xJsn;
        };
        return {
            x2j: function(xml, func) {
              var dfd = new Deferred();
              try {
                 var rezlt = xj(xml);
                 dfd.resolve(rezlt);
                 if(func) {
                   func(rezlt);
                 }
              }
              catch(er) {
                 dfd.reject(er);
              }
              return dfd.promise;
            }
        };
    }());                        

    public by Peter Johnson a.k.a. insertcoffee  78538  0  3  0

    Pelias category counts - OSM planet Apr 29 - 2015

    Pelias category counts - OSM planet Apr 29 - 2015: cat-counts.json
    {
      "took": 344,
      "timed_out": false,
      "_shards": {
        "total": 40,
        "successful": 40,
        "failed": 0
      },
      "hits": {
        "total": 165113284,
        "max_score": 0,
        "hits": [
          
        ]
      },
      "aggregations": {
        "popular": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "retail",
              "doc_count": 2035329
            },
            {
              "key": "food",
              "doc_count": 1052789
            },
            {
              "key": "education",
              "doc_count": 1012070
            },
            {
              "key": "transport",
              "doc_count": 999489
            },
            {
              "key": "recreation",
              "doc_count": 913755
            },
            {
              "key": "nightlife",
              "doc_count": 622372
            },
            {
              "key": "transport:public",
              "doc_count": 618726
            },
            {
              "key": "professional",
              "doc_count": 532643
            },
            {
              "key": "religion",
              "doc_count": 505962
            },
            {
              "key": "government",
              "doc_count": 439336
            },
            {
              "key": "entertainment",
              "doc_count": 438220
            },
            {
              "key": "health",
              "doc_count": 359072
            },
            {
              "key": "accomodation",
              "doc_count": 294060
            },
            {
              "key": "finance",
              "doc_count": 184095
            },
            {
              "key": "transport:rail",
              "doc_count": 121378
            },
            {
              "key": "transport:station",
              "doc_count": 93877
            },
            {
              "key": "transport:air",
              "doc_count": 69042
            },
            {
              "key": "food:regional",
              "doc_count": 41614
            },
            {
              "key": "transport:air:aerodrome",
              "doc_count": 41028
            },
            {
              "key": "food:pizza",
              "doc_count": 31708
            },
            {
              "key": "food:burger",
              "doc_count": 30856
            },
            {
              "key": "food:cuisine:italian",
              "doc_count": 25551
            },
            {
              "key": "transport:bus",
              "doc_count": 21524
            },
            {
              "key": "food:cuisine:chinese",
              "doc_count": 16937
            },
            {
              "key": "food:coffee_shop",
              "doc_count": 13232
            },
            {
              "key": "food:sandwich",
              "doc_count": 11735
            },
            {
              "key": "food:cuisine:german",
              "doc_count": 10021
            },
            {
              "key": "food:cuisine:japanese",
              "doc_count": 8048
            },
            {
              "key": "food:cuisine:mexican",
              "doc_count": 7967
            },
            {
              "key": "food:cuisine:indian",
              "doc_count": 7397
            },
            {
              "key": "food:kebab",
              "doc_count": 7280
            },
            {
              "key": "food:cuisine:american",
              "doc_count": 7203
            },
            {
              "key": "transport:taxi",
              "doc_count": 7138
            },
            {
              "key": "food:cuisine:french",
              "doc_count": 6603
            },
            {
              "key": "food:chicken",
              "doc_count": 6556
            },
            {
              "key": "food:cuisine:asian",
              "doc_count": 6527
            },
            {
              "key": "food:ice_cream",
              "doc_count": 6345
            },
            {
              "key": "food:cuisine:greek",
              "doc_count": 6028
            },
            {
              "key": "transport:sea",
              "doc_count": 5795
            },
            {
              "key": "food:cuisine:thai",
              "doc_count": 4291
            },
            {
              "key": "food:cuisine:international",
              "doc_count": 4203
            },
            {
              "key": "food:sushi",
              "doc_count": 4122
            },
            {
              "key": "food:fish_and_chips",
              "doc_count": 3505
            },
            {
              "key": "food:cuisine:turkish",
              "doc_count": 2660
            },
            {
              "key": "food:steak",
              "doc_count": 2343
            },
            {
              "key": "food:seafood",
              "doc_count": 2315
            },
            {
              "key": "food:cuisine:spanish",
              "doc_count": 2177
            },
            {
              "key": "food:fish",
              "doc_count": 1414
            },
            {
              "key": "food:cuisine:vietnamese",
              "doc_count": 1400
            },
            {
              "key": "food:noodle",
              "doc_count": 1236
            },
            {
              "key": "food:vegetarian",
              "doc_count": 1164
            },
            {
              "key": "food:cuisine:korean",
              "doc_count": 796
            },
            {
              "key": "food:barbecue",
              "doc_count": 746
            },
            {
              "key": "food:donut",
              "doc_count": 740
            },
            {
              "key": "food:friture",
              "doc_count": 740
            },
            {
              "key": "food:cuisine:bavarian",
              "doc_count": 736
            },
            {
              "key": "food:mediterranean",
              "doc_count": 673
            },
            {
              "key": "food:cake",
              "doc_count": 460
            },
            {
              "key": "food:crepe",
              "doc_count": 421
            },
            {
              "key": "food:cuisine:lebanese",
              "doc_count": 362
            },
            {
              "key": "food:curry",
              "doc_count": 314
            },
            {
              "key": "food:cuisine:russian",
              "doc_count": 287
            },
            {
              "key": "food:tapas",
              "doc_count": 272
            },
            {
              "key": "food:bagel",
              "doc_count": 233
            },
            {
              "key": "food:pasta",
              "doc_count": 225
            },
            {
              "key": "food:cuisine:portuguese",
              "doc_count": 218
            },
            {
              "key": "food:sausage",
              "doc_count": 204
            },
            {
              "key": "food:pancake",
              "doc_count": 203
            },
            {
              "key": "food:cuisine:polish",
              "doc_count": 191
            },
            {
              "key": "food:cuisine:african",
              "doc_count": 190
            },
            {
              "key": "food:cuisine:croatian",
              "doc_count": 171
            },
            {
              "key": "food:cuisine:arab",
              "doc_count": 167
            },
            {
              "key": "food:cuisine:malagasy",
              "doc_count": 158
            },
            {
              "key": "food:cuisine:balkan",
              "doc_count": 154
            },
            {
              "key": "food:vegan",
              "doc_count": 153
            },
            {
              "key": "food:cuisine:brazilian",
              "doc_count": 151
            },
            {
              "key": "food:cuisine:caribbean",
              "doc_count": 146
            },
            {
              "key": "food:cuisine:argentinian",
              "doc_count": 136
            },
            {
              "key": "food:cuisine:hungarian",
              "doc_count": 132
            },
            {
              "key": "food:savory_pancakes",
              "doc_count": 108
            },
            {
              "key": "food:cuisine:peruvian",
              "doc_count": 96
            },
            {
              "key": "food:couscous",
              "doc_count": 79
            },
            {
              "key": "food:pie",
              "doc_count": 78
            },
            {
              "key": "food:sub",
              "doc_count": 78
            },
            {
              "key": "food:cuisine:czech",
              "doc_count": 77
            },
            {
              "key": "food:fried_food",
              "doc_count": 69
            },
            {
              "key": "food:cuisine:basque",
              "doc_count": 66
            },
            {
              "key": "food:cuisine:latin_american",
              "doc_count": 54
            },
            {
              "key": "food:cuisine:danish",
              "doc_count": 48
            },
            {
              "key": "food:cuisine:cantonese",
              "doc_count": 44
            },
            {
              "key": "food:cuisine:australian",
              "doc_count": 38
            },
            {
              "key": "food:dessert",
              "doc_count": 37
            },
            {
              "key": "food:empanada",
              "doc_count": 31
            },
            {
              "key": "food:cuisine:pakistani",
              "doc_count": 30
            },
            {
              "key": "food:cuisine:iranian",
              "doc_count": 29
            },
            {
              "key": "food:cuisine:gaucho",
              "doc_count": 27
            },
            {
              "key": "food:wings",
              "doc_count": 27
            },
            {
              "key": "food:cuisine:sichuan",
              "doc_count": 10
            },
            {
              "key": "food:cuisine:mineira",
              "doc_count": 8
            },
            {
              "key": "food:gyro",
              "doc_count": 8
            },
            {
              "key": "food:bougatsa",
              "doc_count": 5
            },
            {
              "key": "food:cuisine:baiana",
              "doc_count": 5
            },
            {
              "key": "food:cuisine:okinawa_ryori",
              "doc_count": 4
            },
            {
              "key": "food:cuisine:capixaba",
              "doc_count": 3
            },
            {
              "key": "food:cuisine:belarusian",
              "doc_count": 2
            },
            {
              "key": "food:cuisine:hunan",
              "doc_count": 2
            },
            {
              "key": "food:cuisine:shandong",
              "doc_count": 2
            }
          ]
        }
      }
    }
    
    

    public by Peter Johnson a.k.a. insertcoffee  75039  0  3  0

    pelias category query

    pelias category query: query.json
    GET /pelias/_search
    {
       "query": {
          "filtered": {
             "query": {
                "match": {
                   "category": {
                      "query": "food retail",
                      "analyzer": "simple", 
                      "operator" : "or"
                   }
                }
             },
             "filter": {
                "bool": {
                   "must": [
                      {
                         "geo_distance": {
                            "distance": "50km",
                            "distance_type": "plane",
                            "optimize_bbox": "indexed",
                            "_cache": true,
                            "center_point": {
                               "lat": 40.74454,
                               "lon": -73.99023
                            }
                         }
                      }
                   ]
                }
             }
          }
       },
       "size": 100,
       "sort": [
          {
             "_geo_distance": {
                "center_point": {
                   "lat": 40.74454,
                   "lon": -73.99023
                },
                "order": "asc",
                "unit": "km"
             }
          }
       ],
       "fields": ["name.default","category"],
       "track_scores": true
    }
    
    

    public by zonaro  3667  6  8  3

    AJAX port for C#

    This is not a genuine Ajax Request but have the same behavior. Simply call the AJAX.GET, AJAX.POST or AJAX.JSON methods.
    public class AJAX
       {
           public static string GET(string URL)
           {
               string data = "";
               if (!string.IsNullOrWhiteSpace(URL))
               {
                   try
                   {
                       WebClient client = new WebClient();
                       client.Encoding = Encoding.UTF8;
                       data = client.DownloadString(URL);
                       client.Dispose();
                   }
                   catch (Exception ex)
                   {
                       data = ex.Message;
                   }
               }
               return data;
    
           }
    
           public byte[] GETFile(string URL)
           {
               using (WebClient Client = new WebClient())
               {
                   return Client.DownloadData(URL);
               }
           }
    
           public object POST(string URL, string PostData)
           {
    
               WebRequest request = WebRequest.Create("");
               request.Method = "POST";
               byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
               request.ContentType = "application/x-www-form-urlencoded";
               request.ContentLength = byteArray.Length;
               Stream dataStream = request.GetRequestStream();
               dataStream.Write(byteArray, 0, byteArray.Length);
               dataStream.Close();
               WebResponse response = request.GetResponse();
               Console.WriteLine(((HttpWebResponse)response).StatusDescription);
               dataStream = response.GetResponseStream();
               StreamReader reader = new StreamReader(dataStream);
               string responseFromServer = reader.ReadToEnd();
               reader.Close();
               dataStream.Close();
               response.Close();
               return responseFromServer;
           }
    
           public void POSTFile(string URL, FileInfo TheFile)
           {
               using (System.Net.WebClient wc = new System.Net.WebClient())
               {
                   wc.UploadFile(URL, TheFile.FullName);
               }
           } 
    
           public static dynamic JSON(string URL)
           {
               string json = GET(URL);
               dynamic result = new JavaScriptSerializer().Deserialize<dynamic>(json);
               return result;
           }
    
    
       }
    

    public by Zenitram.PRO  3598  1  5  1

    How to convert retrieved text in JSON format containing line breaks.

    Using $.ajax, dataType: "JSON".
    function parseline($string){
      $string = str_replace(chr(10), "//n", $string);
      $string = str_replace(chr(13), "//n", $string);
      return $string;
    } 

    public by marceloviana  1593  14  4  0

    Csharp consumindo Rest + lendo JSON

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Net;
    using System.IO;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    namespace ExemploChatBot
    {
        public partial class Chat : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void enviar_Click(object sender, EventArgs e)
            {
                string txt_campo_texto = campo_texto.Text;
    
                var url = "http://128.0.0.1:5000/site?id=2542&texto_digitado="+ txt_campo_texto + "";
    
                var syncClient = new WebClient();
                var content = syncClient.DownloadString(url);            
    
                dynamic registro = JObject.Parse(content);
                campo_texto.Text = registro.pergunta;
    
            }
        }
    }
    • Public Snippets
    • Channels Snippets