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

Python 怎么实现“包装”一个 json??

  •  
  •   gosky · Aug 3, 2023 · 3191 views
    This topic created in 1197 days ago, the information mentioned may be changed or developed.

    一个 dict 或者对象,已经序列化为 json 数据。 现在需要在序列化好的数据外层,加一个包装。

    比如,已有 json 数据:

    {
    	"name": "test"
    }
    

    加包装后的效果:

    {
    	"data": {
    	    "name": "test"
        }
    }
    

    go 语言里有 json.RawMessage 可以做到这点

    11 replies  •  2023-08-04 16:56:23 +08:00
    taotaodaddy
    taotaodaddy
    Aug 3, 2023
    1
    import json

    serialized_data = '{"name": "test"}'
    data = json.loads(serialized_data)

    wrapped_data = {'data': data}

    final_serialized_data = json.dumps(wrapped_data)

    嗯嗯,gpt 给的代码,没运行,看着没毛病
    gosky
    gosky
    OP
    Aug 3, 2023
    2
    @taotaodaddy 谢谢。有没有不 loads 的方案?
    taotaodaddy
    taotaodaddy
    Aug 3, 2023
    3
    难道是:

    data = '{"name": "test"}'
    wrapped_data_str = f'{{"data": {data}}}'

    吗?
    joesonw
    joesonw
    Aug 3, 2023 via iPhone
    4
    这不就是字符串拼接?
    tcpdump
    tcpdump
    Aug 3, 2023
    5
    @joesonw 一个 单引号、双引号就搞挂了
    Aruforce
    Aruforce
    Aug 3, 2023 via Android
    6
    @tcpdump 逐字符判断第一个出现的 '或者"到底是哪个吧……
    ForNickey
    ForNickey
    Aug 3, 2023
    7
    还是用 import json 格式化后再 return 真的一个单双引号能搞死你
    est
    est
    Aug 3, 2023❤️1
    8
    print(json.dumps({'data': type('RawJson', (), {'__repr__': lambda o: '{"a}'})()}, cls=type('EC', (json.JSONEncoder,), {'encode': lambda self,o: str(o)})))
    llwwbb7
    llwwbb7
    Aug 3, 2023
    9
    都写 python 了还在乎 load 一下吗
    ch2
    ch2
    Aug 3, 2023❤️1
    10
    都用 python 了还把最 easy 的 import json 扔了,纯粹买椟还珠
    fionasit007
    fionasit007
    Aug 4, 2023
    11
    这种问题需要来这里问吗,所有语言的基操吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4454 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 06:45 · PVG 14:45 · LAX 22:45 · JFK 01:45
    ♥ Do have faith in what you're doing.