Python L2: String、Class、Json

文章展示了如何在Python中将一个自定义类实例转换为字典和JSON字符串,以及如何对含有特定key的JSON字典数组进行排序。定义了一个Node类,并通过__dict__属性和json.dumps()函数实现了实例到字典和JSON字符串的转换。同时,文章还演示了如何将排序后的字典数组转换回类实例。

定义一个Python class

class Node:
    def __init__(self):
        self.ip = ""
        self.pods = []
        self.count = 0

Json 对象(instance) 转 dict 和字符串 

n = Node()
n.count = 1
n.ip = "127.0.0.1"
n.pods = ["pod-x", "pod-y", "pod-z"]

# Json Object
print(n)         # <__main__.Node instance at 0x7f4eaa078eb0>
print(n.ip)
print(type(n))   # <type 'instance'>

# Json Object to Dict
print(n.__dict__)
print(n.__dict__["ip"])

# Json Object to String
json_str = json.dumps(n.__dict__, indent = 4)
print(json_str)

Json dict 按特定key的value 排序 

n1 = Node()
n1.count = 2
n1.ip = "127.0.0.2"
n1.pods = ["pod-x2", "pod-y2"]

n2 = Node()
n2.count = 3
n2.ip = "127.0.0.2"
n2.pods = ["pod-x3", "pod-y3", "pod-z3"]

nodes = [n, n1, n2]

# json object array to string
nodes_jsonstr = json.dumps(nodes, default = lambda o : o.__dict__, indent=4)
print(nodes_jsonstr)
print(type(nodes_jsonstr))     # <type 'str'>

# json string to dict
json.loads(nodes_jsonstr)

# dict sort
nodes_array = sorted(json.loads(nodes_jsonstr), key = lambda e : e["count"], reverse = False)
print(nodes_array[0])
print(nodes_array[0]['ip'])
print(type(nodes_array[0]))   # <type 'dict'>

 dict似乎无法直接转为Json Object, 但可以实现. 方法

class Dict(dict):
    __setattr__ = dict.__setitem__
    __getattr__ = dict.__getitem__

def dictToObj(dictObj):
    if not isinstance(dictObj, dict):
        return dictObj
    d = Dict()
    for k, v in dictObj.items():
        d[k] = dictToObj(v)

    return d

n_obj = dictToObj(nodes_array[0])
print(n_obj.ip)
print(type(n_obj)) # <class '__main__.Dict'>

<script setup lang="ts"> import { ref, onMounted } from 'vue'; import { NLayout, NLayoutHeader, NLayoutContent, NLayoutFooter, NIcon, NInput, NInputGroup, NButton, NUpload, NCode, NScrollbar, NEmpty, NConfigProvider // 引入配置提供器 } from 'naive-ui'; import { SearchOutline as SearchIcon } from '@vicons/ionicons5'; import hljs from 'highlight.js/lib/core'; import python from 'highlight.js/lib/languages/python'; import 'highlight.js/styles/github.css'; // 导入github主题 // 注册语言 hljs.registerLanguage('python', python); // 可以在这里注册更多语言,如javascript、typescript等 const searchQuery = ref(''); const fileContent = ref(''); const fileName = ref(''); // 根据文件后缀获取语言类型 const getLanguageByExtension = (filename: string) => { const extension = filename.split('.').pop()?.toLowerCase() || ''; const langMap: Record<string, string> = { 'js': 'javascript', 'jsx': 'javascript', 'ts': 'typescript', 'tsx': 'typescript', 'html': 'html', 'css': 'css', 'json': 'json', 'vue': 'html', 'py': 'python', 'java': 'java', 'c': 'c', 'cpp': 'cpp', 'cs': 'csharp', 'php': 'php', 'rb': 'ruby', 'go': 'go', 'rs': 'rust', 'swift': 'swift', 'kt': 'kotlin', 'sh': 'shell', 'md': 'markdown', 'yaml': 'yaml', 'yml': 'yaml', 'xml': 'xml' }; return langMap[extension] || 'text'; }; const handleFileChange = ({ file }: any) => { const selectedFile = file.file as File; if (selectedFile) { if (!selectedFile.type.startsWith('text/') && !selectedFile.name.match(/\.(js|jsx|ts|tsx|html|css|json|vue|py|java|c|cpp|cs|php|rb|go|rs|swift|kt|sh|md|yaml|yml|xml)$/i)) { window.alert('请选择文本或代码文件'); return; } fileName.value = selectedFile.name; searchQuery.value = selectedFile.name; const reader = new FileReader(); reader.onload = (e: ProgressEvent<FileReader>) => { if (e.target?.result) { fileContent.value = e.target.result as string; } }; reader.readAsText(selectedFile); } }; const handleNext = () => { console.log('下一步操作', fileContent.value); window.alert('进入下一步操作!'); }; </script> <template> <!-- 在n-config-provider中注入hljs --> <n-config-provider :hljs="hljs"> <n-layout class="container"> <!-- 顶部图标 --> <n-layout-header class="header"> <n-icon size="48" color="#2080f0"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"> <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/> </svg> </n-icon> <h1 class="title">自动化测试平台</h1> </n-layout-header> <!-- 搜索区域 --> <n-layout-content class="search-section"> <n-input-group> <div class="source-label">Source:</div> <n-input v-model="searchQuery" placeholder="输入文件路径或选择文件" readonly size="large" /> <n-upload action="" :show-file-list="false" @change="handleFileChange" > <n-button type="primary" size="large"> <template #icon> <n-icon><search-icon /></n-icon> </template> 选择文件 </n-button> </n-upload> </n-input-group> </n-layout-content> <n-layout-content class="content-display"> <n-scrollbar style="height: 100%"> <div v-if="fileContent"> <!-- 使用n-code组件,并设置show-line-numbers和word-wrap --> <n-code :code="fileContent" :language="getLanguageByExtension(fileName)" show-line-numbers word-wrap /> </div> <n-empty v-else description="未选择文件" /> </n-scrollbar> </n-layout-content> <!-- 底部操作区域 --> <n-layout-footer class="footer"> <n-button type="primary" size="large" :disabled="!fileContent" @click="handleNext" class="action-button" > 下一步 </n-button> </n-layout-footer> </n-layout> </n-config-provider> </template> <style scoped> .container { height: 100vh; display: flex; flex-direction: column; overflow: hidden; } .header { flex: 0 0 auto; display: flex; flex-direction: column; align-items: center; padding: 15px 0; } .title { font-size: 24px; font-weight: bold; margin-top: 8px; color: #333; } .search-section { flex: 0 0 auto; padding: 10px 0 20px; width: 100%; } .n-input-group { display: flex; align-items: center; width: 100%; padding: 0 20px; box-sizing: border-box; } .source-label { font-size: 16px; font-weight: bold; color: #333; white-space: nowrap; margin-right: 12px; } .content-display { flex: 1; min-height: 0; padding: 0 20px; overflow: auto; /* 单一滚动条控制 */ } .code-container { background: #f5f5f5; border-radius: 4px; padding: 15px; max-height: calc(100vh - 250px); /* 动态高度计算 */ } /* 覆盖n-code的样式,确保背景色一致 */ :deep(.n-code) { background: #f5f5f5 !important; padding: 15px; font-size: 15px; line-height: 1.5; max-height: 100%; overflow: auto; } :deep(.n-code-line) { white-space: pre-wrap !important; word-break: break-word !important; } .footer { flex: 0 0 auto; display: flex; justify-content: flex-end; padding: 15px 20px; width: 100%; box-sizing: border-box; } .action-button { box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); } @media (max-width: 768px) { .search-section, .content-display, .footer { padding-left: 10px; padding-right: 10px; } .n-input-group { flex-direction: column; align-items: flex-start; } .source-label { margin-bottom: 8px; margin-right: 0; } .n-upload { margin-top: 10px; width: 100%; } .n-button { width: 100%; } .action-button { width: 100%; margin-top: 10px; } } </style>上面代码发错了,是改这个代码给我修改样式和布局,这个页面我在鼠标往下滚动的时候会出现两个滚动条(因为父组件已经有了)如果这个页面再来一黑色的滚动条,特别丑,所以给我修改,保留父组件的滚动条,把这个子页面的滚动条删除或者隐藏掉,使其屏幕上只有一个滚动条,返回完整代码
最新发布
10-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值