Python实现Json文件转为点表示法(Dot-Notation)

将Json转换为点表示法有很多用途,本文基于Python实现一个简单demo来转换。

【原文见我的博客,如有更新请博客园的不一定及时同步改:https://blog.jfz.me/2023/python-json-to-dot-notation.html

{
    "vehicle": {
        "car": {
            "bmw": true,
            "audi": 1,
            "ford": "also good"
        },
        "truck": {
            "all": "cool"
        }
    }
}

转为:

$.vehicle.car.ford : also good
$.vehicle.car.bmw : True
$.vehicle.car.audi : 1
$.vehicle.truck.all : cool

代码:

#! /usr/bin/env python
import json
import pyperclip

def getKeys(val, old="$"):
    if isinstance(val, dict):
        for k in val.keys():
            getKeys(val[k], old + "." + str(k))
    elif isinstance(val, list):
        for i,k in enumerate(val):
            getKeys(k, old + "." + str(i))
    else:
        print("{} : {}".format(old,str(val)))

data = json.loads(pyperclip.paste())
getKeys(data)

参考:

https://techtldr.com/convert-json-to-dot-notation-with-python/

posted @ 2023-04-07 22:42  Sandeepin  阅读(108)  评论(0编辑  收藏  举报