How to use the simplejson.loads function in simplejson

To help you get started, we’ve selected a few simplejson examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github serverdensity / sd-agent / tests / core / test_emitter.py View on Github external
"metric": "%d" % i,  # use an integer so that it's easy to find the metric afterwards
                "points": [(i, i)],
                "source_type_name": "System",
            } for i in xrange(nb_series)
        ]}

        compressed_payloads = serialize_and_compress_metrics_payload(metrics_payload, max_compressed_size, 0, log)

        # check that all the payloads are smaller than the max size
        for compressed_payload in compressed_payloads:
            self.assertLess(len(compressed_payload), max_compressed_size)

        # check that all the series are there (correct number + correct metric names)
        series_after = []
        for compressed_payload in compressed_payloads:
            series_after.extend(json.loads(compressed_payload)["series"])

        self.assertEqual(nb_series, len(series_after))

        metrics_sorted = sorted([int(metric["metric"]) for metric in series_after])
        for i, metric_name in enumerate(metrics_sorted):
            self.assertEqual(i, metric_name)
github tav / assetgen / assetgen / main.py View on Github external
def sourcemap(self, js, sm_path, sm_id, src_map):
        data = dec_json(read(sm_path))
        if self.sm_root:
            data['sourceRoot'] = self.sm_root
        sources = []; add_source = sources.append
        if self.cs or self.ts:
            base_mapping = self.base_mapping
            for source in data['sources']:
                add_source(src_map[base_mapping[source]])
        else:
            for source in data['sources']:
                add_source(src_map[source])
        data['sources'] = sources
        path_new = self.emit(self.path+self.sm_ext, ')]}\n' + enc_json(data))
        map_str = '//@ sourceMappingURL=%s' % sm_id
        map_str_new = '//@ sourceMappingURL=%s' % path_new
        self.emit(self.path, js.replace(map_str, map_str_new))
github foobnix / foobnix / src / foobnix / thirdparty / vkontakte / api.py View on Github external
self.api_secret = api_secret
        self.opener = opener
        self.defaults = defaults
        self.method_prefix = ''
        
        url = opener.open("http://vkontakte.ru/login.php?app=2234333&layout=popup&type=browser&settings=26")
        url = url.geturl()
        
        logging.debug(url)    
        url = urllib.url2pathname(url)    
        id = url.find("session=")
        url = url[id+len("session="):]
    
        logging.debug(url)
        try:
            self.json =  simplejson.loads(url)        
            logging.debug(json)
            self.my_user_id =self.json['mid']
        except Exception, e:
            logging.error("Error decoding url %s" % url)
            logging.error(e);
github rtyler / Spawning / spawning / spawning_controller.py View on Github external
if len(positional_args) < 1 and not options.restart_args:
        parser.error("At least one argument is required. "
            "For the default factory, it is the dotted path to the wsgi application "
            "(eg my_package.my_module.my_wsgi_application). For the paste factory, it "
            "is the ini file to load. Pass --help for detailed information about available options.")

    if options.backdoor:
        try:
            eventlet.spawn(eventlet.backdoor.backdoor_server, eventlet.listen(('localhost', 3000)))
        except Exception, ex:
            sys.stderr.write('**> Error opening backdoor: %s\n' % ex)

    sock = None

    if options.restart_args:
        restart_args = json.loads(options.restart_args)
        factory = restart_args['factory']
        factory_args = restart_args['factory_args']

        start_delay = restart_args.get('start_delay')
        if start_delay is not None:
            factory_args['start_delay'] = start_delay
            print "(%s) delaying startup by %s" % (os.getpid(), start_delay)
            time.sleep(start_delay)

        fd = restart_args.get('fd')
        if fd is not None:
            sock = socket.fromfd(restart_args['fd'], socket.AF_INET, socket.SOCK_STREAM)
            ## socket.fromfd doesn't result in a socket object that has the same fd.
            ## The old fd is still open however, so we close it so we don't leak.
            os.close(restart_args['fd'])
        return start_controller(sock, factory, factory_args)
github DataDog / dd-agent / checks.d / kubernetes.py View on Github external
def _update_pods_metrics(self, instance, pods):
        supported_kinds = [
            "DaemonSet",
            "Deployment",
            "Job",
            "ReplicationController",
            "ReplicaSet",
        ]

        controllers_map = defaultdict(int)
        for pod in pods['items']:
            try:
                created_by = json.loads(pod['metadata']['annotations']['kubernetes.io/created-by'])
                kind = created_by['reference']['kind']
                if kind in supported_kinds:
                    controllers_map[created_by['reference']['name']] += 1
            except KeyError:
                continue

        tags = instance.get('tags', [])
        for ctrl, pod_count in controllers_map.iteritems():
            _tags = tags[:]  # copy base tags
            _tags.append('kube_replication_controller:{0}'.format(ctrl))
            self.publish_gauge(self, NAMESPACE + '.pods.running', pod_count, _tags)
github zenodo / zenodo / openaire / lib / openaire_deposit_engine.py View on Github external
Example of dictionary::

        {
            "fundedby": "CIP-EIP",
            "end_date": "2012-08-31",
            "title": "Advanced Biotech Cluster platforms for Europe",
            "acronym": "ABCEUROPE",
            "call_identifier": "EuropeINNOVA-ENT-CIP-09-C-N01S00",
            "ec_project_website": null,
            "grant_agreement_number": "245628",
            "start_date": "2009-09-01"
        }
    """
    info = get_kb_mapping(CFG_OPENAIRE_PROJECT_INFORMATION_KB, str(projectid))
    if info:
        return json_unicode_to_utf8(json.loads(info['value']))
    else:
        return {}
github fedelemantuano / tika-app-python / tikapp / tikapp.py View on Github external
Args:
            path (string): Path of file to analyze
            payload (string): Payload base64 to analyze
            objectInput (object): file object/standard input to analyze
            pretty_print (boolean): If True adds newlines and whitespace,
                                    for better readability
            convert_to_obj (boolean): If True convert JSON in object
        """
        f = file_path(path, payload, objectInput)
        switches = ["-j", "-r", f]
        if not pretty_print:
            switches.remove("-r")
        result = self._command_template(switches)

        if result and convert_to_obj:
            result = json.loads(result, encoding="utf-8")

        return result, path, f
github karpathy / researchpooler / google_search.py View on Github external
def getPDFURL(pdf_title):
    """
    Search google for exact match of the title of this paper 
    and return the url to the pdf file, or 'notfound' if no exact match was 
    found.
    
    pdf_title: string, name of the paper.
    Returns url to the PDF, or 'notfound' if unsuccessful
    """
    
    # get results in JSON
    query = urllib.urlencode({'q' : pdf_title + ' filetype:pdf'})
    url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
          % (query)
    search_results = urllib.urlopen(url)
    json = simplejson.loads(search_results.read())
    results = json['responseData']['results']
    
    # sift through them in search of an exact match
    for r in results:
        if r['title'] == '<b>' + pdf_title + '</b>':
            return r['url']
    
    return 'notfound'
github mozilla / treeherder / treeherder / etl / management / commands / import_project_credentials.py View on Github external
def handle(self, *args, **options):

        if not (os.path.exists(args[0]) and os.path.isfile(args[0])):
            raise CommandError("Credentials file not found: %s" % args[0])
        with open(args[0]) as credentials_file:
            credentials = json.loads(credentials_file.read())
            ds_list = Datasource.objects.filter(project__in=credentials.keys())
            datasource_dict = dict((ds.project, ds) for ds in ds_list)
            for project, cred in credentials.items():
                if project in datasource_dict:
                    datasource_dict[project].oauth_consumer_key = cred['consumer_key']
                    datasource_dict[project].oauth_consumer_secret = cred['consumer_secret']
                    datasource_dict[project].save()
        self.stdout.write("Credentials loaded successfully")
github UDST / urbansim / synthicity / urbansimd / urbansimd2-pandas.py View on Github external
def resp(estimate,simulate):
    print "Request: %s\n" % request.query.json
    req = simplejson.loads(request.query.json)
    returnobj = misc.run_model(req,DSET,estimate=estimate,simulate=simulate,variables=variables)
    return returnobj 
  estimate = int(request.query.get('estimate',1))