如何使用python将yaml块转换为json块?

时间:2017-03-12 19:17:29

标签: python json yaml

我有这个生成yaml数据的脚本。我需要它来生成等效的json数据。

代码是这样的:

def main(argv):
        global top
        global version
        global package
        librivox_rest_url       = 'unknown'
        app_image_url           = 'unknown'
        password                = 'XXXXXXX'
        try:
              opts, args = getopt.getopt(argv,"hl:t:v:k:p:i:",["url=","top=","version=","package=","password=","image_url="])
        except getopt.GetoptError:
              print 'make_hiera_data_from_librivox_api.py -l <librvox url> [-t <top>] [-v <version>] [-p <password>]'
              sys.exit(2)
        for opt, arg in opts:
                if opt == '-h':
                        usage ( 'Help called' )
                        sys.exit(0)
                elif opt in ("-l", "--url"):
                        librivox_rest_url = arg
                elif opt in ("-t", "--top"):
                        top = arg
                elif opt in ("-v", "--version"):
                        version = arg
                elif opt in ("-p", "--password"):
                        password = arg
                elif opt in ("-k", "--package"):
                        password = arg
                elif opt in ("-i", "--image_url"):
                        app_image_url = arg

        if ( librivox_rest_url == 'unknown' ):
                usage ("Please specify a librivox api url")
                sys.exit (1)
        if ( app_image_url == 'unknown' ):
                usage ("Please specify the app image url")
                sys.exit (1)

        parsed          = json.loads(requests.get(librivox_rest_url).text)
        book_key        = parsed['books'].keys()[0]
        apptitle        = parsed['books'][book_key]['title']
        app_image_url   = app_image_url
        app_zip_url     = parsed['books'][book_key]['url_zip_file']
        description     = parsed['books'][book_key]['description']
        yaml_version = """---
top: '%s'
package: '%s'
version: %s
password: '%s'
make_audiobook::package_name: "%%{hiera('package')}"
make_audiobook::description::description: %s

make_audiobook::version: "%%{hiera('version')}"
make_audiobook::mp3filesdir: "%%{hiera('top')}/%%{::appname}/%%{::appname}/res/raw"
make_audiobook::app_image::app_image_url: '%s'
make_audiobook::app_image::resource_path:  "%%{hiera('top')}/%%{::appname}/%%{::appname}"
make_audiobook::app_image::appdir:  "%%{hiera('top')}/%%{::appname}"
make_audiobook::app_image::appname:  "%%{::appname}"
make_audiobook::app_javacode::appname:          "%%{::appname}"
make_audiobook::app_javacode::password:         "%%{hiera('password')}"
make_audiobook::app_javacode::apptitle:         "%s"
make_audiobook::app_javacode::package:          "%%{hiera('package')}"
make_audiobook::app_javacode::path_to_code:     "%%{hiera('top')}/%%{::appname}/%%{::appname}/src/com/%%{hiera('package')}/%%{::appname}"
make_audiobook::app_javacode::path_to_androidmanifest:     "%%{hiera('top')}/%%{::appname}/%%{::appname}"
make_audiobook::app_javacode::version:          "%%{hiera('version')}"
make_audiobook::app_javacode::tracks: """ % (top, package, version, password, description.encode('ascii', 'ignore').decode('ascii'), app_image_url, apptitle)

        for thing in get_filenames_from_zip_file (app_zip_url):
                if ( thing ):
                        yaml_version += " - %s\n" % thing

        print '''
make_audiobook::app_javacode::track_titles:
        '''.strip()
        for thing in parsed['books'][book_key]['sections']:
                yaml_version += " - %s\n" % (thing['title'])

        yaml_version += """
make_audiobook::create_project::workspace: "%%{hiera('top')}/%%{::appname}"
make_audiobook::create_project::appname: "%%{::appname}"
make_audiobook::create_project::package_name: "%%{hiera('package')}"
make_audiobook::create_project::android: '/home/plankton/android-sdk-linux/tools/android'

make_audiobook::generate_keystore::top: "%%{hiera('top')}"
make_audiobook::generate_keystore::password: "%%{hiera('password')}"
make_audiobook::ant_debug::workspace: "%%{hiera('top')}/%%{::appname}"

make_audiobook::app_mp3files::app_zip_url: '%s'
make_audiobook::app_mp3files::resource_path:  "%%{hiera('top')}/%%{::appname}/%%{::appname}"

make_audiobook::app_drawables::path_to_drawables:  "%%{hiera('top')}/%%{::appname}/%%{::appname}/res/drawable-hdpi"
""" % (app_zip_url)

        print yaml_version
        print json.dumps( yaml_version, sort_keys=True, indent=2)

当我运行脚本时,我得到这个输出,其中json数据只是一个很长的行。我做错了什么?

make_audiobook::app_javacode::track_titles:
---
top: '/home/get_links/TEMPLATE_FILES'
package: 'redcricket'
version: 1
password: 'XXXXXXX'
make_audiobook::package_name: "%{hiera('package')}"
make_audiobook::description::description: <p>"The Art of War is a Chinese military treatise written during the 6th century BC by Sun Tzu. Composed of 13 chapters, each of which is devoted to one aspect of warfare, it has long been praised as the definitive work on military strategies and tactics of its time. The Art of War is one of the oldest and most famous studies of strategy and has had a huge influence on both military planning and beyond. The Art of War has also been applied, with much success, to business and managerial strategies." (summary from Wikipedia)</p>

make_audiobook::version: "%{hiera('version')}"
make_audiobook::mp3filesdir: "%{hiera('top')}/%{::appname}/%{::appname}/res/raw"
make_audiobook::app_image::app_image_url: 'https://ia801509.us.archive.org/7/items/song_of_the_wave_1703_librivox/songwave_1703.jpg'
make_audiobook::app_image::resource_path:  "%{hiera('top')}/%{::appname}/%{::appname}"
make_audiobook::app_image::appdir:  "%{hiera('top')}/%{::appname}"
make_audiobook::app_image::appname:  "%{::appname}"
make_audiobook::app_javacode::appname:          "%{::appname}"
make_audiobook::app_javacode::password:         "%{hiera('password')}"
make_audiobook::app_javacode::apptitle:         "Art of War"
make_audiobook::app_javacode::package:          "%{hiera('package')}"
make_audiobook::app_javacode::path_to_code:     "%{hiera('top')}/%{::appname}/%{::appname}/src/com/%{hiera('package')}/%{::appname}"
make_audiobook::app_javacode::path_to_androidmanifest:     "%{hiera('top')}/%{::appname}/%{::appname}"
make_audiobook::app_javacode::version:          "%{hiera('version')}"
make_audiobook::app_javacode::tracks:  - art_of_war_01-02_sun_tzu_64kb
 - art_of_war_03-04_sun_tzu_64kb
 - art_of_war_05-06_sun_tzu_64kb
 - art_of_war_07-08_sun_tzu_64kb
 - art_of_war_09-10_sun_tzu_64kb
 - art_of_war_11_sun_tzu_64kb
 - art_of_war_12-13_sun_tzu_64kb
 - 01 - Laying Plans / 02 - Waging War
 - 03 - Attack By Stratagem / 04 - Tactical Dispositions
 - 05 - Energy / 06 - Weak Points and Strong
 - 07 - Maneuvering / 08 - Variation in Tactics
 - 09 - The Army on the March / 10 - Terrain
 - 11 - The Nine Situations
 - 12 - The Attack By Fire / 13 - The Use of Spies

make_audiobook::create_project::workspace: "%{hiera('top')}/%{::appname}"
make_audiobook::create_project::appname: "%{::appname}"
make_audiobook::create_project::package_name: "%{hiera('package')}"
make_audiobook::create_project::android: '/home/plankton/android-sdk-linux/tools/android'

make_audiobook::generate_keystore::top: "%{hiera('top')}"
make_audiobook::generate_keystore::password: "%{hiera('password')}"
make_audiobook::ant_debug::workspace: "%{hiera('top')}/%{::appname}"

make_audiobook::app_mp3files::app_zip_url: 'http://www.archive.org/download/art_of_war_librivox/art_of_war_librivox_64kb_mp3.zip'
make_audiobook::app_mp3files::resource_path:  "%{hiera('top')}/%{::appname}/%{::appname}"

make_audiobook::app_drawables::path_to_drawables:  "%{hiera('top')}/%{::appname}/%{::appname}/res/drawable-hdpi"

"---\ntop: '/home/get_links/TEMPLATE_FILES'\npackage: 'redcricket'\nversion: 1\npassword: 'XXXXXXX'\nmake_audiobook::package_name: \"%{hiera('package')}\"\nmake_audiobook::description::description: <p>\"The Art of War is a Chinese military treatise written during the 6th century BC by Sun Tzu. Composed of 13 chapters, each of which is devoted to one aspect of warfare, it has long been praised as the definitive work on military strategies and tactics of its time. The Art of War is one of the oldest and most famous studies of strategy and has had a huge influence on both military planning and beyond. The Art of War has also been applied, with much success, to business and managerial strategies.\" (summary from Wikipedia)</p>\n\nmake_audiobook::version: \"%{hiera('version')}\"\nmake_audiobook::mp3filesdir: \"%{hiera('top')}/%{::appname}/%{::appname}/res/raw\"\nmake_audiobook::app_image::app_image_url: 'https://ia801509.us.archive.org/7/items/song_of_the_wave_1703_librivox/songwave_1703.jpg'\nmake_audiobook::app_image::resource_path:  \"%{hiera('top')}/%{::appname}/%{::appname}\"\nmake_audiobook::app_image::appdir:  \"%{hiera('top')}/%{::appname}\"\nmake_audiobook::app_image::appname:  \"%{::appname}\"\nmake_audiobook::app_javacode::appname:          \"%{::appname}\"\nmake_audiobook::app_javacode::password:         \"%{hiera('password')}\"\nmake_audiobook::app_javacode::apptitle:         \"Art of War\"\nmake_audiobook::app_javacode::package:          \"%{hiera('package')}\"\nmake_audiobook::app_javacode::path_to_code:     \"%{hiera('top')}/%{::appname}/%{::appname}/src/com/%{hiera('package')}/%{::appname}\"\nmake_audiobook::app_javacode::path_to_androidmanifest:     \"%{hiera('top')}/%{::appname}/%{::appname}\"\nmake_audiobook::app_javacode::version:          \"%{hiera('version')}\"\nmake_audiobook::app_javacode::tracks:  - art_of_war_01-02_sun_tzu_64kb\n - art_of_war_03-04_sun_tzu_64kb\n - art_of_war_05-06_sun_tzu_64kb\n - art_of_war_07-08_sun_tzu_64kb\n - art_of_war_09-10_sun_tzu_64kb\n - art_of_war_11_sun_tzu_64kb\n - art_of_war_12-13_sun_tzu_64kb\n - 01 - Laying Plans / 02 - Waging War\n - 03 - Attack By Stratagem / 04 - Tactical Dispositions\n - 05 - Energy / 06 - Weak Points and Strong\n - 07 - Maneuvering / 08 - Variation in Tactics\n - 09 - The Army on the March / 10 - Terrain\n - 11 - The Nine Situations\n - 12 - The Attack By Fire / 13 - The Use of Spies\n\nmake_audiobook::create_project::workspace: \"%{hiera('top')}/%{::appname}\"\nmake_audiobook::create_project::appname: \"%{::appname}\"\nmake_audiobook::create_project::package_name: \"%{hiera('package')}\"\nmake_audiobook::create_project::android: '/home/plankton/android-sdk-linux/tools/android'\n\nmake_audiobook::generate_keystore::top: \"%{hiera('top')}\"\nmake_audiobook::generate_keystore::password: \"%{hiera('password')}\"\nmake_audiobook::ant_debug::workspace: \"%{hiera('top')}/%{::appname}\"\n\nmake_audiobook::app_mp3files::app_zip_url: 'http://www.archive.org/download/art_of_war_librivox/art_of_war_librivox_64kb_mp3.zip'\nmake_audiobook::app_mp3files::resource_path:  \"%{hiera('top')}/%{::appname}/%{::appname}\"\n\nmake_audiobook::app_drawables::path_to_drawables:  \"%{hiera('top')}/%{::appname}/%{::appname}/res/drawable-hdpi\" \n"

1 个答案:

答案 0 :(得分:1)

生成yaml:

import yaml
data = {...}  # python datastructure
yaml.dump(data, default_flow_style=False)  # second parameter specifies block style yaml.

生成很好的缩进json:

print json.dumps(data, indent=4)

如果你有yaml并想要json:

print json.dumps(yaml.load(...), indent=4)