search

Home  >  Q&A  >  body text

python - 使用json.loads,key不带引号,且value中可能含有“:”,如何最好地处理?

例如:

'''{
    colorSize: [{
        "Color": "超窄边IPS",
        "SkuId": 1365289,
        "Size": "27英寸"
    }, {
        "Color": "21:9超宽IPS曲面",
        "SkuId": 1742140,
        "Size": "29英寸"
    }, {
        "Color": "17英寸(TN,5:4方屏)",
        "SkuId": 1032147,
        "Size": "17英寸"
    }],
    warestatus: 1,
    shangjiazizhi: false
}'''

为了给key加双引号,必需先选中之
因为内容带有“:”,

  1. (\w+):,误处理"21:9超宽IPS曲面"

  2. [{,]\s*(\w+):,误处理"17英寸(TN,5:4方屏)"

有什么比较好的处理方法呢?

怪我咯怪我咯2863 days ago855

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:18:41

    Can be useddemjson https://github.com/dmeranda/d...

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:18:41

    Two solutions
    One uses demjson as @raidou said
    One uses pyexecjs
    Upload the code

    import execjs
    import demjson
    
    str = '''
    {
        colorSize: [{
            "Color": "超窄边IPS",
            "SkuId": 1365289,
            "Size": "27英寸"
        }, {
            "Color": "21:9超宽IPS曲面",
            "SkuId": 1742140,
            "Size": "29英寸"
        }, {
            "Color": "17英寸(TN,5:4方屏)",
            "SkuId": 1032147,
            "Size": "17英寸"
        }],
        warestatus: 1,
        shangjiazizhi: false
    }
    '''
    print demjson.decode(str)
    print execjs.eval(str)

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:18:41

    The mobile version can’t see the full title, can you reply?
    The mobile version can’t reply to comments yet, I’m annoyed.
    Update it to match a space in front of it

    \s([^"]+):

    or match the beginning of a line in front

    ^([^"]+):

    reply
    0
  • PHPz

    PHPz2017-04-18 09:18:41

    I solved it myself, let me put it simply:
    The most important thing is these crazy :号必然出现在成对的"li

    Because double quotes always appear in pairs and do not cross
    Use re.sub to filter pairs of double quotes, and then filter the results to the function for processing: replace the colon between the double quotes with special characters. For the convenience of description, I will This character is called

    Replace the result without content colon with the previous regular processing with colon

    Then a new question comes. After adding double quotes to the key, if I want to replace 替换回:,那么 back to :, then what special character should I choose for ?

    🎜

    reply
    0
  • Cancelreply