推荐学习书目
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 · 2641 views
    This topic created in 1017 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
        1
    taotaodaddy  
       Aug 3, 2023
    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
       Aug 3, 2023
    @taotaodaddy 谢谢。有没有不 loads 的方案?
    taotaodaddy
        3
    taotaodaddy  
       Aug 3, 2023
    难道是:

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

    吗?
    joesonw
        4
    joesonw  
       Aug 3, 2023 via iPhone
    这不就是字符串拼接?
    tcpdump
        5
    tcpdump  
       Aug 3, 2023
    @joesonw 一个 单引号、双引号就搞挂了
    Aruforce
        6
    Aruforce  
       Aug 3, 2023 via Android
    @tcpdump 逐字符判断第一个出现的 '或者"到底是哪个吧……
    ForNickey
        7
    ForNickey  
       Aug 3, 2023
    还是用 import json 格式化后再 return 真的一个单双引号能搞死你
    est
        8
    est  
       Aug 3, 2023   ❤️ 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  
       Aug 3, 2023
    都写 python 了还在乎 load 一下吗
    ch2
        10
    ch2  
       Aug 3, 2023   ❤️ 1
    都用 python 了还把最 easy 的 import json 扔了,纯粹买椟还珠
    fionasit007
        11
    fionasit007  
       Aug 4, 2023
    这种问题需要来这里问吗,所有语言的基操吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1058 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 18:34 · PVG 02:34 · LAX 11:34 · JFK 14:34
    ♥ Do have faith in what you're doing.