V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
krisbai
V2EX  ›  Python

请教下 Python 的 json 格式问题

  •  
  •   krisbai · 2017-03-22 16:21:36 +08:00 · 1630 次点击
    这是一个创建于 2584 天前的主题,其中的信息可能已经有所发展或是发生改变。
    希望的效果 :
    {
    "data": [
    {
    "{#SITEURL}": "127.0.0.1,code,port",
    "{#SITEPORT}": "9931"
    }
    ]


    实际的效果:
    {
    "data": [
    {
    "{#SITEURL}": "127.0.0.1,code,port"
    },
    {
    "{#SITEPORT}": "9931"
    }
    ]


    脚本 :
    #!/usr/bin/env python
    #encoding=utf8
    import os
    import json
    active_url = file('/etc/zabbix/script/discovery/active_url.txt')
    active_port = file('/etc/zabbix/script/discovery/active_port.txt')
    d01 = []
    for url in active_url.readlines():
    for port in active_port.readlines():
    d01.append({"{#SITEURL}": url.strip()}),
    d01.append({"{#SITEPORT}": port.strip()})
    print json.dumps({'data': d01},{'data': d01}, sort_keys=True, indent=4, separators=(',', ': '))
    4 条回复    2017-03-22 16:45:03 +08:00
    ltux
        1
    ltux  
       2017-03-22 16:34:40 +08:00
    跟 python 没关系,跟你写的代码有关系。想往字典里加 key:value 就去操作字典,不要用 list 的 append()。
    krisbai
        2
    krisbai  
    OP
       2017-03-22 16:37:52 +08:00
    @ltux 嗯 ,刚看文章 明白了 append 的用法 ,谢啦!
    dipahole
        3
    dipahole  
       2017-03-22 16:40:40 +08:00
    _dict = {"{#SITEURL}": url.strip() ,"{#SITEPORT}": port.strip()}
    d01.append(_dict)
    krisbai
        4
    krisbai  
    OP
       2017-03-22 16:45:03 +08:00
    @dipahole 谢谢你!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3182 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 13:18 · PVG 21:18 · LAX 06:18 · JFK 09:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.