推荐学习书目
› 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
wico77
V2EX  ›  Python

python 如何合并两个 json 文件

  •  
  •   wico77 · Feb 10, 2015 · 20326 views
    This topic created in 4299 days ago, the information mentioned may be changed or developed.

    RT
    不是合并两个普通文件。是json文件,合并后成为一个大的json文件

    13 replies  •  2015-02-11 17:13:46 +08:00
    kslr
    kslr
    Feb 10, 2015 via Android
    1
    Load dict
    Kilerd
    Kilerd
    Feb 11, 2015 via Android
    2
    先转成两个dict,然后合并,再转成json
    ricorico
    ricorico
    Feb 11, 2015 via iPad
    3
    先 read,然后 json.loads,之后调用 dict 的 update 方法合并?
    要考虑有没有相同的 key,不知道具体要求…
    wico77
    wico77
    OP
    Feb 11, 2015
    4
    @ricorico
    import glob
    import json

    files = glob.glob('*.json')
    result = []
    for file in files:
    f = open(file,'r')
    a = json.load(f)
    for b in a:
    result.append(b)

    print len(result)

    outfile = json.dumps(result)

    这样对吗
    NeoAtlantis
    NeoAtlantis
    Feb 11, 2015❤️1
    5
    怎么合并……json不一定是dict的形式,也可以一开始就是list呢,也可以就是字符串或者Boolean或者数字呢……看你要求了,不过一般来说用json那个库应该能搞定。
    NeoAtlantis
    NeoAtlantis
    Feb 11, 2015
    6


    以上都是合法的json内容
    icedx
    icedx
    Feb 11, 2015
    7
    @ricorico 正解
    Septembers
    Septembers
    Feb 11, 2015
    8
    import json
    json.dump(open('target.json'), [json.load(open('source1.json')), json.load(open('source2.json'))])
    Septembers
    Septembers
    Feb 11, 2015❤️1
    9
    import json
    json.dump([json.load(open('source1.json')), json.load(open('source2.json'))], open('target.json'))
    invite
    invite
    Feb 11, 2015
    10
    要哪种合并?有一种合并是这样的:
    两个文件a和b,内容为 A 和 B,那么合并后:

    {'a': A , 'b': B}

    多快好省,哈哈。
    leiz
    leiz
    Feb 11, 2015
    11
    完全没有上下文的问题为什么会有这么多人回答?
    fanta
    fanta
    Feb 11, 2015
    12
    import ast
    ast.literal_eval(json)
    wico77
    wico77
    OP
    Feb 11, 2015
    13
    @Septembers 这个就是我想要的。谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2285 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 13:56 · PVG 21:56 · LAX 05:56 · JFK 08:56
    ♥ Do have faith in what you're doing.