Python json.JSONDecoder() Examples

The following are code examples for showing how to use json.JSONDecoder(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: IntentionPrediction   Author: djp42   File: util.py    MIT License 6 votes vote down vote up
def loadJSONDict(jsonFilePath):

    # Read in the JSON file containing data
    fullJsonString = None
    with open(jsonFilePath, 'r') as f:
        fullJsonString = f.read().encode('ascii', errors='ignore')

    # Read the JSON file in as a dictionary
    print(f)
    d = json.JSONDecoder()
    returnDict = d.decode(fullJsonString)

    return returnDict

##
# Function: loadJSONDicts
# -----------------------
# Loads multiple JSON files into python dictionaries and returns 
# a list of those dictionaries.
## 
Example 2
Project: antlr-ast   Author: datacamp   File: test_marshalling.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_marshalling(ast):
    # Given
    code = "not 2"
    correct_json = load(open("tests/json/test_marshalling/test_marshalling.json"))

    # When
    ast_tree = ast.parse(code)
    json_tree = dumps(ast_tree, cls=AstEncoder)

    # Then
    assert loads(json_tree) == correct_json
    ast_tree = JSONDecoder(object_hook=get_decoder()).decode(json_tree)
    assert isinstance(ast_tree, ast.AstNode)
    assert isinstance(ast_tree.children_by_field["NOT"], str)
    assert isinstance(ast_tree.NOT, str)
    assert isinstance(ast_tree.children_by_field["expr"], ast.AstNode)
    assert isinstance(ast_tree.expr, ast.AstNode) 
Example 3
Project: coa_tools   Author: ndee85   File: addon_updater.py    GNU General Public License v3.0 6 votes vote down vote up
def get_api(self, url):
        # return the json version
        get = None
        get = self.get_raw(url)
        if get != None:
            try:
                return json.JSONDecoder().decode(get)
            except Exception as e:
                self._error = "API response has invalid JSON format"
                self._error_msg = str(e.reason)
                self._update_ready = None
                return None
        else:
            return None


    # create a working directory and download the new files 
Example 4
Project: beam   Author: axbaretto   File: patch.py    Apache License 2.0 6 votes vote down vote up
def patch_notebook(full_path):
  # Replace the branch repo URL.
  lines = []
  with open(full_path) as f:
    for line in f:
      if colab_url in line or github_url in line:
        line = branch_repo_re.sub(target_branch_repo, line)
      lines += [line]
  content = ''.join(lines)

  # Add the license block.
  decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict)
  elements = decoder.decode(content).items()
  first_key, _ = elements[0]
  if first_key != 'license':
    print('Patching {}'.format(full_path))
    elements.insert(0, ('license', license_text))

  # Overwrite the file with the new contents.
  with open(full_path, 'w') as f:
    json.dump(collections.OrderedDict(elements), f, indent=2) 
Example 5
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def readJSONString(self, skipContext):
    string = []
    if skipContext is False:
      self.context.read()
    self.readJSONSyntaxChar(QUOTE)
    while True:
      character = self.reader.read()
      if character == QUOTE:
        break
      if character == ESCSEQ[0]:
        character = self.reader.read()
        if character == ESCSEQ[1]:
          self.readJSONSyntaxChar(ZERO)
          self.readJSONSyntaxChar(ZERO)
          character = json.JSONDecoder().decode('"\u00%s"' % self.trans.read(2))
        else:
          off = ESCAPE_CHAR.find(char)
          if off == -1:
            raise TProtocolException(TProtocolException.INVALID_DATA,
                                     "Expected control char")
          character = ESCAPE_CHAR_VALS[off]
      string.append(character)
    return ''.join(string) 
Example 6
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def main_function(gist_filename, gist_description, gist_body):

    gist_post_data = {  'description': gist_description, 
                        'public': True,
                        'files': {gist_filename: {'content': gist_body}}}

    json_post_data = json.dumps(gist_post_data).encode('utf-8')

    def get_gist_url(found_json):
        wfile = json.JSONDecoder()
        wjson = wfile.decode(found_json)
        print('https://gist.github.com/' + wjson['id'])

    def upload_gist():
        print('sending')
        url = 'https://api.github.com/gists'
        json_to_parse = urlopen(url, data=json_post_data)
        
        print('received response from server')
        found_json = json_to_parse.readall().decode()
        get_gist_url(found_json)

    upload_gist() 
Example 7
Project: numcodecs   Author: zarr-developers   File: json.py    MIT License 6 votes vote down vote up
def __init__(self, encoding='utf-8', skipkeys=False, ensure_ascii=True,
                 check_circular=True, allow_nan=True, sort_keys=True, indent=None,
                 separators=None, strict=True):
        self._text_encoding = encoding
        if separators is None:
            # ensure separators are explicitly specified, and consistent behaviour across
            # Python versions, and most compact representation if indent is None
            if indent is None:
                separators = ',', ':'
            else:
                separators = ', ', ': '
        separators = tuple(separators)
        self._encoder_config = dict(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
                                    check_circular=check_circular, allow_nan=allow_nan,
                                    indent=indent, separators=separators,
                                    sort_keys=sort_keys)
        self._encoder = _json.JSONEncoder(**self._encoder_config)
        self._decoder_config = dict(strict=strict)
        self._decoder = _json.JSONDecoder(**self._decoder_config) 
Example 8
Project: bitmask-dev   Author: leapcode   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def json_loads(data):
    """
    It works as json.loads but supporting multiple encodings in the same
    string and accepting an `str` parameter that won't be converted to unicode.

    :param data: the string to load the objects from
    :type data: str

    :returns: the corresponding python object result of parsing 'data', this
              behaves similarly as json.loads, with the exception of that
              returns always `str` instead of `unicode`.
    """
    obj = None
    with CustomJsonScanner():
        # We need to use the cls parameter in order to trigger the code
        # that will let us control the string parsing method.
        obj = json.loads(data, cls=json.JSONDecoder)

    return obj 
Example 9
Project: airflow-api   Author: uptake   File: variables.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get(self):
        """Get all variables in Airflow"""
        with airflow_sql_alchemy_session() as session:
            airflow_variables = session.query(Variable).all()
        var_list = []
        d = json.JSONDecoder()
        for var in airflow_variables:
            val = None
            deserialize_json = True
            try:
                val = d.decode(var.val)
            except Exception:
                val = var.val
                deserialize_json = False
            var_list.append({
                NAME_KEY: var.key,
                VALUE_KEY: val,
                DESERIALIZE_JSON_KEY: deserialize_json
            })
        return Response(
            response=json.dumps(var_list),
            status=GET_RESPONSE_SUCCESS_CODE,
            mimetype=JSON_MIME_TYPE
        ) 
Example 10
Project: python-sdk   Author: optimizely   File: condition.py    Apache License 2.0 6 votes vote down vote up
def object_hook(self, object_dict):
        """ Hook which when passed into a json.JSONDecoder will replace each dict
    in a json string with its index and convert the dict to an object as defined
    by the passed in condition_decoder. The newly created condition object is
    appended to the conditions_list.

    Args:
      object_dict: Dict representing an object.

    Returns:
      An index which will be used as the placeholder in the condition_structure
    """
        instance = self.decoder(object_dict)
        self.condition_list.append(instance)
        self.index += 1
        return self.index 
Example 11
Project: python-sdk   Author: optimizely   File: condition.py    Apache License 2.0 6 votes vote down vote up
def loads(conditions_string):
    """ Deserializes the conditions property into its corresponding
  components: the condition_structure and the condition_list.

  Args:
    conditions_string: String defining valid and/or conditions.

  Returns:
    A tuple of (condition_structure, condition_list).
    condition_structure: nested list of operators and placeholders for operands.
    condition_list: list of conditions whose index correspond to the values of the placeholders.
  """
    decoder = ConditionDecoder(_audience_condition_deserializer)

    # Create a custom JSONDecoder using the ConditionDecoder's object_hook method
    # to create the condition_structure as well as populate the condition_list
    json_decoder = json.JSONDecoder(object_hook=decoder.object_hook)

    # Perform the decoding
    condition_structure = json_decoder.decode(conditions_string)
    condition_list = decoder.condition_list

    return (condition_structure, condition_list) 
Example 12
Project: zabbix-scripts   Author: lordievader   File: test_discover_ssl.py    GNU General Public License v3.0 6 votes vote down vote up
def test_discover_ssl(mocker):
    """Checks if discover_ssl returns valid json.
    """
    assert json.JSONDecoder().decode(discover_ssl.main()) == {'data': []}

    output = {
        'data': [
            {
                '{#URL}': 'example.org',
                '{#PORT}': '443',
            },
            {
                '{#URL}': 'example.org',
                '{#PORT}': '8080',
            },
        ]
    }
    with open('tests/urls.txt', 'r') as urls:
        with mocker.patch.object(discover_ssl, 'open', return_value=urls):
            assert json.JSONDecoder().decode(discover_ssl.main()) == output 
Example 13
Project: dimod   Author: dwavesystems   File: json.py    Apache License 2.0 6 votes vote down vote up
def dimod_object_hook(obj):
    """JSON-decoding for dimod objects.

    See Also:
        :class:`json.JSONDecoder` for using custom decoders.

    """
    if _is_sampleset_v2(obj):
        # in the future we could handle subtypes but right now we just have the
        # one
        return SampleSet.from_serializable(obj)
    elif _is_bqm(obj):
        # in the future we could handle subtypes but right now we just have the
        # one
        return BinaryQuadraticModel.from_serializable(obj)
    return obj 
Example 14
Project: blender-power-sequencer   Author: GDQuest   File: addon_updater.py    GNU General Public License v3.0 6 votes vote down vote up
def get_api(self, url):
		# return the json version
		get = None
		get = self.get_raw(url)
		if get != None:
			try:
				return json.JSONDecoder().decode(get)
			except Exception as e:
				self._error = "API response has invalid JSON format"
				self._error_msg = str(e.reason)
				self._update_ready = None
				print(self._error, self._error_msg)
				return None
		else:
			return None


	# create a working directory and download the new files 
Example 15
Project: airflow   Author: apache   File: variable_command.py    Apache License 2.0 6 votes vote down vote up
def _variable_export_helper(filepath):
    """Helps export all of the variables to the file"""
    var_dict = {}
    with db.create_session() as session:
        qry = session.query(Variable).all()

        data = json.JSONDecoder()
        for var in qry:
            try:
                val = data.decode(var.val)
            except Exception:  # pylint: disable=broad-except
                val = var.val
            var_dict[var.key] = val

    with open(filepath, 'w') as varfile:
        varfile.write(json.dumps(var_dict, sort_keys=True, indent=4))
    print("{} variables successfully exported to {}".format(len(var_dict), filepath)) 
Example 16
Project: moviecatcher   Author: EvilCult   File: BdApi.py    MIT License 6 votes vote down vote up
def getPlayUrl (self, taskID) :
		taskID = str(taskID)
		bdApi = 'https://yun.baidu.com/rest/2.0/services/cloud_dl?need_task_info=1&status=255&start=0&limit=10&method=list_task&app_id=250528&channel=chunlei&web=1&app_id=250528&bdstoken={}&clienttype=0'.format(self.bdInfo['token'])
		html = self.Tools.getPage(bdApi, self.requestHeader)
		if html['code'] == '200' : 
			body =  html['body']
		else :
			body =  html['body']

		info = json.JSONDecoder().decode(body)
		taskInfo = info['task_info']

		try:
			for x in taskInfo :
				if taskID == x['task_id'] :
					savePath = urllib.quote(x['save_path'].encode("UTF8"))
					playUrl = 'https://yun.baidu.com/play/video#video/path=' + savePath
					break 
		except Exception as e:
			playUrl = ''

		return (playUrl) 
Example 17
Project: json-stream   Author: sebcat   File: jstream.py    MIT License 6 votes vote down vote up
def json_objects(readable):
    """ Generator producing a stream of JSON objects from a file-like object

    Should only be used for lists or objects, as literal values may be split 
    between read buffers and decoded as separate values (e.g., 1234 -> 12, 34 
    if 1234 ends upp crossing a buffer boundary)
    """
    dec = json.JSONDecoder()
    buf = readable.read(BUFSIZE)
    while True:
        buf = buf.lstrip(WHITESPACE)
        try:
            obj, off = dec.raw_decode(buf)
            yield obj
            buf = buf[off:]
        except ValueError:
            chunk = readable.read(BUFSIZE)
            if len(chunk) == 0:
                break
            else:
                buf += chunk 
Example 18
Project: apicultor   Author: sonidosmutantes   File: FreesoundDB.py    GNU General Public License v3.0 6 votes vote down vote up
def get_access_token(self, client_id, client_secret, auth_code):
        """
            Aquire an OAuth2 access token
            To be run one time (then use refresh token)
        """
        # curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&code=THE_GIVEN_CODE" https://www.freesound.org/apiv2/oauth2/access_token/
        data = "client_id=%(client_id)s&client_secret=%(client_secret)s&grant_type=authorization_code&code=%(auth_code)s"%locals()
        print data
        request = urllib2.Request( 'https://www.freesound.org/apiv2/oauth2/access_token/', data=data )
        # request.add_header('Accept', 'application/json')
        # try:
        response = urllib2.urlopen(request)
        # except urllib2.HTTPError, exc:
        #     if exc.code == 401: # Unauthorized
        #         raise Unauthorized("Bad request")

        return json.JSONDecoder().decode(response) 
Example 19
Project: apicultor   Author: sonidosmutantes   File: FreesoundDB.py    GNU General Public License v3.0 6 votes vote down vote up
def refresh_token(self, client_id, client_secret, refresh_token):
        """
        To get a new access token using your refresh token you basically need to repeat Step 3 setting the grant_type parameter to ‘refresh_token’ (instead of ‘authorization_code’) and adding a refresh_token parameter with your refresh token (instead of adding the code parameter with the authorization code). See the following example:
# curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" "https://www.freesound.org/apiv2/oauth2/access_token/"
        """
        data = "client_id=%(client_id)s&client_secret=%(client_secret)s&grant_type=refresh_token&refresh_token=%(refresh_token)s"%locals()
        print data
        request = urllib2.Request( 'https://www.freesound.org/apiv2/oauth2/access_token/', data=data )
        # request.add_header('Accept', 'application/json')
        # try:
        response = urllib2.urlopen(request)
        # except urllib2.HTTPError, exc:
        #     if exc.code == 401: # Unauthorized
        #         raise Unauthorized("Bad request")
        print(response)
        return json.JSONDecoder().decode(response) 
Example 20
Project: docker-airflow   Author: abhioncbr   File: views.py    Apache License 2.0 6 votes vote down vote up
def action_varexport(self, ids, session=None):
        V = models.Variable
        qry = session.query(V).filter(V.id.in_(ids)).all()

        var_dict = {}
        d = json.JSONDecoder()
        for var in qry:
            val = None
            try:
                val = d.decode(var.val)
            except:
                val = var.val
            var_dict[var.key] = val

        response = make_response(json.dumps(var_dict, sort_keys=True, indent=4))
        response.headers["Content-Disposition"] = "attachment; filename=variables.json"
        return response 
Example 21
Project: pysphere   Author: rnbguy   File: misphere.py    MIT License 5 votes vote down vote up
def recv_handler(self):
        while self.recv_handle_live:
            r, _, _ = select.select([self.socket], [], [], 0.5)
            if r:
                resps = self.socket.recv(512).decode()
                while True:
                    resp_dict, idx = json.JSONDecoder().raw_decode(resps)
                    self.resp_handler(resp_dict)
                    if idx >= len(resps):
                        break
                    else:
                        resps = resps[idx:] 
Example 22
Project: quart   Author: pgjones   File: __init__.py    MIT License 5 votes vote down vote up
def loads(object_: str, app: Optional["Quart"] = None, **kwargs: Any) -> Any:
    json_decoder: Type[json.JSONDecoder] = JSONDecoder
    if app is None and _app_ctx_stack.top is not None:  # has_app_context requires a circular import
        app = current_app._get_current_object()

    if app is not None:
        json_decoder = app.json_decoder
        if _request_ctx_stack.top is not None:  # has_request_context requires a circular import
            blueprint = app.blueprints.get(request.blueprint)
            if blueprint is not None and blueprint.json_decoder is not None:
                json_decoder = blueprint.json_decoder
    kwargs.setdefault("cls", json_decoder)

    return json.loads(object_, **kwargs) 
Example 23
Project: zamia-prolog   Author: gooofy   File: logic.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def json_to_prolog(jstr):
    return json.JSONDecoder(object_hook = _prolog_from_json).decode(jstr) 
Example 24
Project: helios_lib   Author: anarvote   File: serializer.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs) 
Example 25
Project: crosswalk-odroid-ucc   Author: UCC-Organism   File: manifest_json_parser.py    MIT License 5 votes vote down vote up
def __init__(self, input_path):
    self.input_path = input_path
    input_file = file(self.input_path)
    try:
      input_src = input_file.read()
      self.data_src = json.JSONDecoder().decode(input_src)
      self.ret_dict = self._output_items()
    except IOError:
      raise Exception('Error in decoding json-format manifest file.')
    except KeyError:
      raise Exception('Wrong keyword in json-format manifest file.')
    finally:
      input_file.close() 
Example 26
Project: antlr-ast   Author: datacamp   File: test_expr_ast.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_text_none_and_self_text():
    # Given
    code = "not 2"
    ast_tree = parse(code)
    json_tree = json.dumps(ast_tree, cls=AstEncoder)
    from_json_ast_tree = json.JSONDecoder(object_hook=get_decoder()).decode(json_tree)

    # When
    text = from_json_ast_tree.get_text()

    # Then
    assert text == "not2" 
Example 27
Project: twiltate   Author: KualiCo   File: victorOps.py    MIT License 5 votes vote down vote up
def __init__(self, vo_user, vo_pass, vo_org):
        self.session = requests.Session()
        self.session.headers['Accept'] = 'application/json'
        self.session.auth = (vo_user, vo_pass)
        self.org = vo_org
        self.oncalllist = {}
        self.contact_info = {}
        self.decoder = json.JSONDecoder() 
Example 28
Project: eventsourcing   Author: johnbywater   File: factory.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def construct_sqlalchemy_eventstore(
    session: Any,
    sequenced_item_class: Optional[Type[NamedTuple]] = None,
    sequence_id_attr_name: Optional[str] = None,
    position_attr_name: Optional[str] = None,
    json_encoder_class: Optional[Type[JSONEncoder]] = None,
    json_decoder_class: Optional[Type[JSONDecoder]] = None,
    cipher: Optional[AESCipher] = None,
    record_class: Optional[type] = None,
    contiguous_record_ids: bool = False,
    application_name: Optional[str] = None,
    pipeline_id: int = DEFAULT_PIPELINE_ID,
) -> EventStore:
    sequenced_item_class = sequenced_item_class or StoredEvent  # type: ignore
    sequenced_item_mapper = SequencedItemMapper[DomainEvent](
        sequenced_item_class=sequenced_item_class,
        sequence_id_attr_name=sequence_id_attr_name,
        position_attr_name=position_attr_name,
        json_encoder_class=json_encoder_class,
        json_decoder_class=json_decoder_class,
        cipher=cipher,
    )
    factory = SQLAlchemyInfrastructureFactory(
        session=session,
        integer_sequenced_record_class=record_class or StoredEventRecord,
        sequenced_item_class=sequenced_item_class,
        contiguous_record_ids=contiguous_record_ids,
        application_name=application_name,
        pipeline_id=pipeline_id,
    )
    record_manager = factory.construct_integer_sequenced_record_manager()
    event_store = EventStore[DomainEvent, AbstractRecordManager](
        record_manager=record_manager, event_mapper=sequenced_item_mapper
    )
    return event_store 
Example 29
Project: eventsourcing   Author: johnbywater   File: sequenceditemmapper.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(
        self,
        sequenced_item_class: Optional[Type[NamedTuple]] = None,
        sequence_id_attr_name: Optional[str] = None,
        position_attr_name: Optional[str] = None,
        json_encoder_class: Optional[Type[JSONEncoder]] = None,
        json_decoder_class: Optional[Type[JSONDecoder]] = None,
        cipher: Optional[AESCipher] = None,
        compressor: Any = None,
        other_attr_names: Tuple[str, ...] = (),
    ):
        if sequenced_item_class is not None:
            self.sequenced_item_class = sequenced_item_class
        else:
            self.sequenced_item_class = SequencedItem  # type: ignore
        self.json_encoder_class = json_encoder_class or ObjectJSONEncoder
        self.json_encoder = self.json_encoder_class(
            separators=JSON_SEPARATORS, sort_keys=True
        )
        self.json_decoder_class = json_decoder_class or ObjectJSONDecoder
        self.json_decoder = self.json_decoder_class()
        self.cipher = cipher
        self.compressor = compressor
        self.field_names = SequencedItemFieldNames(self.sequenced_item_class)
        self.sequence_id_attr_name = (
            sequence_id_attr_name or self.field_names.sequence_id
        )
        self.position_attr_name = position_attr_name or self.field_names.position
        self.other_attr_names = other_attr_names or self.field_names.other_names 
Example 30
Project: eventsourcing   Author: johnbywater   File: factory.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(
        self,
        record_manager_class: Optional[Type[AbstractRecordManager]] = None,
        sequenced_item_class: Optional[Type[NamedTuple]] = None,
        event_store_class: Optional[Type[AbstractEventStore]] = None,
        sequenced_item_mapper_class: Optional[Type[AbstractSequencedItemMapper]] = None,
        json_encoder_class: Optional[Type[JSONEncoder]] = None,
        json_decoder_class: Optional[Type[JSONDecoder]] = None,
        integer_sequenced_record_class: Optional[type] = None,
        timestamp_sequenced_record_class: Optional[type] = None,
        snapshot_record_class: Optional[type] = None,
        contiguous_record_ids: bool = False,
        application_name: Optional[str] = None,
        pipeline_id: int = DEFAULT_PIPELINE_ID,
    ):
        self.record_manager_class = (
            record_manager_class or type(self).record_manager_class
        )
        self.event_store_class = event_store_class or type(self).event_store_class
        self.sequenced_item_class = (
            sequenced_item_class or type(self).sequenced_item_class
        )
        self.sequenced_item_mapper_class = (
            sequenced_item_mapper_class or type(self).sequenced_item_mapper_class
        )
        self.json_encoder_class = json_encoder_class or type(self).json_encoder_class
        self.json_decoder_class = json_decoder_class or type(self).json_decoder_class

        self._integer_sequenced_record_class = integer_sequenced_record_class

        self._timestamp_sequenced_record_class = timestamp_sequenced_record_class

        self._snapshot_record_class = snapshot_record_class

        self.contiguous_record_ids = contiguous_record_ids
        self.application_name = application_name
        self.pipeline_id = pipeline_id 
Example 31
Project: eventsourcing   Author: johnbywater   File: notificationlog.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(
        self, base_url: str, json_decoder_class: Optional[Type[JSONDecoder]] = None
    ):
        """
        Initialises remote notification log object.

        :param str base_url: A URL for the HTTP API.
        :param JSONDecoder json_decoder_class: used to deserialize remote sections.
        """
        self.base_url = base_url
        json_decoder_class_ = json_decoder_class or ObjectJSONDecoder
        self.json_decoder = json_decoder_class_()
        self._section_size = -1 
Example 32
Project: resolwe   Author: genialis   File: run.py    Apache License 2.0 5 votes vote down vote up
def iterjson(text):
    """Decode JSON stream."""
    decoder = json.JSONDecoder()
    while text:
        obj, ndx = decoder.raw_decode(text)

        if not isinstance(obj, dict):
            raise ValueError()

        text = text[ndx:].lstrip('\r\n')
        yield obj 
Example 33
Project: TESTGIT   Author: B-ROY   File: cookie.py    Apache License 2.0 5 votes vote down vote up
def load_data(self):
        try:
            data = self.request.get_signed_cookie(self.prefix)
        except KeyError:
            data = None
        except BadSignature:
            raise WizardViewCookieModified('WizardView cookie manipulated')
        if data is None:
            return None
        return json.loads(data, cls=json.JSONDecoder) 
Example 34
Project: lib-esrijson   Author: geoadmin   File: codec.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def load(fp,
         cls=json.JSONDecoder,
         parse_constant=_enforce_strict_numbers,
         object_hook=esrijson.base.EsriJSON.to_instance,
         **kwargs):
    return json.load(fp,
                     cls=cls, object_hook=object_hook,
                     parse_constant=parse_constant,
                     **kwargs) 
Example 35
Project: lib-esrijson   Author: geoadmin   File: codec.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def loads(s,
          cls=json.JSONDecoder,
          parse_constant=_enforce_strict_numbers,
          object_hook=esrijson.base.EsriJSON.to_instance,
          **kwargs):
    return json.loads(s,
                      cls=cls, object_hook=object_hook,
                      parse_constant=parse_constant,
                      **kwargs) 
Example 36
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def load_jira_data(project_key, username, password):
        """
        Load the data from jira, and build a list that has the details you want in the OmniFocus notes.

        :param project_key: 3-4 letter jira project key (project letters in front of the issue number)
        :param username: jira username
        :param password: jira password
        :return:
        """
        data = []
        url = '{0}rest/api/2/search?jql=project='.format(JIRA_URL) + \
              '{0}&maxResults=1000&os_username={1}&os_password={2}'.format(project_key, username, password)
        f = urlopen(url)
        response = f.read()
        f.close()
        jira_data = JSONDecoder().decode(response)
        for issue in jira_data['issues']:
            key = issue['key']
            url = '{0}{1}'.format(JIRA_URL, key)
            name = issue['fields']['assignee']['name']
            title = issue['fields']['summary'].replace('"', "'")
            status = issue['fields']['status']['name']
            dueDate = stringToDatetime(issue['fields']['duedate'])
            if issue['fields']['description']:
                description = issue['fields']['description'].encode('ascii', 'ignore').replace('"', "'")\
                    .replace("\\'", "'")
            else:
                description = ''
            # Build the task details and store them on the data
            task = '{0}: {1}'.format(key, title)
            note = 'Status: {0}\n{1}\n\n{2}'.format(status, url, description)
            data.append({'key': key, 'task': task, 'name': name, 'status': status, 'dueDate': dueDate, 'note': note})
        return data 
Example 37
Project: http-image-jpeg   Author: nils-soderman   File: addon_updater.py    GNU General Public License v3.0 5 votes vote down vote up
def get_api(self, url):
		# return the json version
		get = None
		get = self.get_api_raw(url) # this can fail by self-created error raising
		if get != None:
			return json.JSONDecoder().decode( get )
		else:
			return None


	# create a working directory and download the new files 
Example 38
Project: zvt   Author: zvtvz   File: sedes.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs) 
Example 39
Project: finac   Author: alttch   File: core.py    MIT License 5 votes vote down vote up
def core_method(f):
    import inspect
    argspec = inspect.getfullargspec(f)

    @wraps(f)
    def do(*args, **kwargs):
        if config.api_uri is not None:
            import requests
            import uuid
            import json
            payload = {
                'jsonrpc': '2.0',
                'method': f.__name__,
                'params': kwargs,
                'id': str(uuid.uuid4())
            }
            if config.api_key is not None:
                payload['params']['_k'] = config.api_key
            for i, a in enumerate(args):
                payload['params'][argspec.args[i]] = a
            r = requests.post(config.api_uri,
                              json=payload,
                              timeout=config.api_timeout)
            if not r.ok:
                raise RuntimeError('Finac server error: {}'.format(
                    r.status_code))
            result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(
                r.text)
            if 'error' in result:
                raise _exceptions.get(result['error']['code'], RuntimeError)(
                    result['error'].get('message'))
            return result['result']
        else:
            return f(*args, **kwargs)

    return do 
Example 40
Project: pyramid-zappa-api-boilerplate   Author: web-masons   File: default.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kargs):
        JSONDecoder.__init__(self, object_hook=self.dict_to_object, *args, **kargs) 
Example 41
Project: istaflow   Author: shaun-h   File: FlowManager.py    MIT License 5 votes vote down vote up
def get_element_details_for_flow(self, flow):
		with open(self.dir+flow,'r') as f:
			return json.JSONDecoder().decode(f.read())['elements'] 
Example 42
Project: istaflow   Author: shaun-h   File: FlowManager.py    MIT License 5 votes vote down vote up
def get_type_for_flow(self, flow):
		with open(self.dir+flow,'r') as f:
			return json.JSONDecoder().decode(f.read())['type'] 
Example 43
Project: istaflow   Author: shaun-h   File: SettingsManager.py    MIT License 5 votes vote down vote up
def load_file(self):
		if not os.path.isfile(self.filename):
			g = open(self.filename,'w+')
			g.write(json.JSONEncoder().encode({}))
			g.close()
		with open(self.filename,'r') as f:
			self.data = json.JSONDecoder().decode(f.read()) 
Example 44
Project: openshift-restclient-python   Author: openshift   File: discovery.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, client, *args, **kwargs):
        self.client = client
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs) 
Example 45
Project: clusterfuzz   Author: google   File: json_utils.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
    super(JSONDecoder, self).__init__(
        object_hook=self.dict_to_object, *args, **kwargs) 
Example 46
Project: clusterfuzz   Author: google   File: json_utils.py    Apache License 2.0 5 votes vote down vote up
def loads(obj, *args, **kwargs):
  """Custom json.loads using custom encoder JSONDecoder defined in this file."""
  kwargs['cls'] = JSONDecoder
  return json.loads(obj, *args, **kwargs) 
Example 47
Project: Blockly-rduino-communication   Author: technologiescollege   File: serializer.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, *args, **kwargs)
        self.parse_string = _parse_string

        # we need to recreate the internal scan function ..
        self.scan_once = scanner.py_make_scanner(self)

        # .. and we have to explicitly use the Py version,
        # not the C version, as the latter won't work
        # self.scan_once = scanner.make_scanner(self) 
Example 48
Project: cc-crawl-statistics   Author: commoncrawl   File: crawlstats.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kargs):
        json.JSONDecoder.__init__(self, object_hook=self.dict_to_object,
                                  *args, **kargs) 
Example 49
Project: kuyruk-manager   Author: cenkalti   File: __init__.py    MIT License 5 votes vote down vote up
def _failed_tasks(self):
        tasks = self.requeue.redis.hvals('failed_tasks')
        tasks = [t.decode('utf-8') for t in tasks]
        decoder = json.JSONDecoder()
        tasks = map(decoder.decode, tasks)
        return tasks 
Example 50
Project: nanopores   Author: mitschabaude   File: fields.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)