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
gosky
V2EX  ›  Python

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

  •  
  •   gosky · 268 天前 · 1781 次点击
    这是一个创建于 268 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    比如,已有 json 数据:

    {
    	"name": "test"
    }
    

    加包装后的效果:

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

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

    11 条回复    2023-08-04 16:56:23 +08:00
    taotaodaddy
        1
    taotaodaddy  
       268 天前
    import json

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

    wrapped_data = {'data': data}

    final_serialized_data = json.dumps(wrapped_data)

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

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

    吗?
    joesonw
        4
    joesonw  
       268 天前 via iPhone
    这不就是字符串拼接?
    tcpdump
        5
    tcpdump  
       268 天前
    @joesonw 一个 单引号、双引号就搞挂了
    Aruforce
        6
    Aruforce  
       268 天前 via Android
    @tcpdump 逐字符判断第一个出现的 '或者"到底是哪个吧……
    ForNickey
        7
    ForNickey  
       268 天前
    还是用 import json 格式化后再 return 真的一个单双引号能搞死你
    est
        8
    est  
       268 天前   ❤️ 1
    print(json.dumps({'data': type('RawJson', (), {'__repr__': lambda o: '{"a}'})()}, cls=type('EC', (json.JSONEncoder,), {'encode': lambda self,o: str(o)})))
    llwwbb7
        9
    llwwbb7  
       268 天前
    都写 python 了还在乎 load 一下吗
    ch2
        10
    ch2  
       268 天前   ❤️ 1
    都用 python 了还把最 easy 的 import json 扔了,纯粹买椟还珠
    fionasit007
        11
    fionasit007  
       267 天前
    这种问题需要来这里问吗,所有语言的基操吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2969 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 78ms · UTC 13:20 · PVG 21:20 · LAX 06:20 · JFK 09:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.