python - 使用json.loads,key不带引号,且value中可能含有“:”,如何最好地处理?
怪我咯
怪我咯 2017-04-18 09:16:41
0
4
816

例如:

'''{
    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方屏)"

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

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(4)
洪涛

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

Peter_Zhu

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)
Peter_Zhu

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

^([^"]+):
PHPzhong

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 ?

🎜
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!