Print metadata as JSON strings.
482774
def main(args=None):
    """"""
    args = sys.argv[1:]
    parser = argparse.ArgumentParser()
    parser.add_argument("safe_file", type=str, nargs='+')
    parser.add_argument("--granules", action="store_true")
    parsed = parser.parse_args(args)

    pp = pprint.PrettyPrinter()
    for safe_file in parsed.safe_file:
        with s2reader.open(safe_file) as safe_dataset:
            if parsed.granules:
                pp.pprint(
                    dict(
                        safe_file=safe_file,
                        granules=[
                            dict(
                                granule_identifier=granule.granule_identifier,
                                footprint=str(granule.footprint),
                                srid=granule.srid,
                                # cloudmask_polys=str(granule.cloudmask),
                                # nodata_mask=str(granule.nodata_mask),
                                cloud_percent=granule.cloud_percent
                                )
                            for granule in safe_dataset.granules
                            ]
                        )
                    )
            else:
                pp.pprint(
                    dict(
                        safe_file=safe_file,
                        product_start_time=safe_dataset.product_start_time,
                        product_stop_time=safe_dataset.product_stop_time,
                        generation_time=safe_dataset.generation_time,
                        footprint=str(safe_dataset.footprint),
                        bounds=str(safe_dataset.footprint.bounds),
                        granules=len(safe_dataset.granules),
                        granules_srids=list(set([
                            granule.srid
                            for granule in safe_dataset.granules
                            ]))
                        )
                    )
            print "\n"
1216752
def write_json_to_file(json_data, filename="metadata"):
    
    logger_jsons.info("enter write_json_to_file")
    json_data = rm_empty_fields(json_data)
    # Use demjson to maintain unicode characters in output
    json_bin = demjson.encode(json_data, encoding='utf-8', compactly=False)
    # Write json to file
    try:
        open("{}.jsonld".format(filename), "wb").write(json_bin)
        logger_jsons.info("wrote data to json file")
    except FileNotFoundError as e:
        print("Error: Writing json to file: {}".format(filename))
        logger_jsons.debug("write_json_to_file: FileNotFound: {}, {}".format(filename, e))
    logger_jsons.info("exit write_json_to_file")
    return
132237
def transfer_metadata_to_dict(self, meta):
        
        dic = {}
        arr = meta.strip(' ,').split(',')
        for i in arr:
            temp = i.split('=')
            key = temp[0].strip()
            value = temp[1].strip()
            dic[key] = value
        return dic
1307202
def json_pretty_print(s):
    ''''''
    s = json.loads(s)
    return json.dumps(s,
                      sort_keys=True,
                      indent=4,
                      separators=(',', ': '))
579178
def json_dumps(self, obj):
        """"""
        return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
1179903
def load_metadata(fileobj):
        
        with gzip.GzipFile(fileobj=fileobj, mode='r') as z:
            return json.loads(z.readline())
383052
def _write_metadata(self):
        
        string_buffer = StringIO()
        writer = csv.writer(string_buffer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        writer.writerow(['Path *', 'Title *', 'Source ID', 'Description', 'Author', 'Language', 'License ID *', 'License Description', 'Copyright Holder', 'Thumbnail'])
        for k in self.map:
            node = self.map[k]
            writer.writerow([k, node['title'], node['source_id'], node['description'], node['author'], node['language'], node['license'], node['license_description'], node['copyright_holder'], node['thumbnail']])

        self.zf.writestr('Content.csv', string_buffer.getvalue())
173555
def parse_metadata_string(metadata_string):
        """"""
        regex = r"STOP_DATE.+?VALUE\s*=\s*\"(.+?)\""
        match = re.search(regex, metadata_string, re.DOTALL)
        end_time_str = match.group(1)
        return end_time_str
928586
def c_metadata(api, args, verbose=False):
    
    obj = api.get_object(args['<URL>'].split('/')[-1])
    if not set_metadata(args['<JSON>'], obj):
        return json.dumps(obj.metadata.read(), indent=4)
241518
def __meta_metadata(self, field, key):
        """"""
        mf = ''
        try:
            mf = str([f[key] for f in self.metadata
                     if f['field_name'] == field][0])
        except IndexError:
            print("%s not in metadata field:%s" % (key, field))
            return mf
        else:
            return mf
615745
def load_output_meta(self):
        
        options = self.options
        file_path = os.path.join(options.inputdir, 'output.meta.json')
        with open(file_path) as infile:
            return json.load(infile)
124345
def render_json(self):
        ''

        types = {0: 'unknown',
                 1: 'extension',
                 2: 'theme',
                 3: 'dictionary',
                 4: 'langpack',
                 5: 'search',
                 8: 'webapp'}
        output = {'detected_type': types[self.detected_type],
                  'ending_tier': self.ending_tier,
                  'success': not self.failed(),
                  'messages': [],
                  'errors': len(self.errors),
                  'warnings': len(self.warnings),
                  'notices': len(self.notices),
                  'message_tree': self.message_tree,
                  'compatibility_summary': self.compat_summary,
                  'signing_summary': self.signing_summary,
                  'metadata': self.metadata}

        messages = output['messages']

        # Copy messages to the JSON output
        for error in self.errors:
            error['type'] = 'error'
            messages.append(error)

        for warning in self.warnings:
            warning['type'] = 'warning'
            messages.append(warning)

        for notice in self.notices:
            notice['type'] = 'notice'
            messages.append(notice)

        # Output the JSON.
        return json.dumps(output)
232255
def encode_metadata(self):
        
        encoded_list = []
        for key, value in iteritems(self.metadata):
            key_str = str(key)  # dict keys may be of any object type.

            # confirm that the key does not contain unwanted characters.
            if re.search(r'^$|[\s,]+', key_str):
                msg = 'Upload-metadata key "{}" cannot be empty nor contain spaces or commas.'
                raise ValueError(msg.format(key_str))

            value_bytes = b(value)  # python 3 only encodes bytes
            encoded_list.append('{} {}'.format(key_str, b64encode(value_bytes).decode('ascii')))
        return encoded_list
293407
def get_metadata():
    
    misc_path = pkg_resources.resource_filename('hwrt', 'misc/')
    wm_symbols = os.path.join(misc_path, 'wm_symbols.csv')
    wm_tags = os.path.join(misc_path, 'wm_tags.csv')
    wm_tags2symbols = os.path.join(misc_path, 'wm_tags2symbols.csv')
    return {'symbols': read_csv(wm_symbols),
            'tags': read_csv(wm_tags),
            'tags2symbols': read_csv(wm_tags2symbols)}
862197
def _read_routine_metadata(self):
        
        metadata = {}
        if os.path.isfile(self._metadata_filename):
            with open(self._metadata_filename, 'r') as file:
                metadata = json.load(file)

        return metadata
1277206
def get_ladders_metadata(session, parsed):
    """"""
    ladders = {}
    for ladder in parsed.find_all('a', href=re.compile(LADDER_URL_REGEX)):
        ladders[ladder.text] = get_ladder_metadata(session, ladder['href'])
    return ladders
173407
def json_data(self):
        """"""
        return {
            "info_in_id": self.info_in_id,
            "info_out_id": self.info_out_id,
            "node_id": self.node_id,
            "network_id": self.network_id,
        }