命令行 - 使用每个JSON对象的正规表达式创建key-value对并将它附加到JSON对象的文件中

分享于 

3分钟阅读

ubuntu

  繁體

问题:

文件示例


{"Name" :"%Hana-29-Mrs-Smith","job":"engineer"}


{"Name" :"%Mike-31-Mr-Larry","job":"marketing"}


{"Name" :"%Jhon-40-Mr-Doe","job":"engineer"}



所需输出:


{"Name" :"%Hana-29-Mr-Smith", "f_nams":"Hana", "age":29, "title":"Mrs", "l_name":"Smith","job":"engineer"}


{"Name" :"%Mike-29-Mr-Larry", "f_nams":"Mike", "age":31, "title":"Mr", "l_name":"Larry","job":"marketing"}


{"Name" :"%Jhon-29-Mr-Smith", "f_nams":"Jhon", "age":40, "title":"Mr", "l_name":"Doe","job":"engineer"}




答案1:

对于此类非嵌套对象,可以考虑使用Miller


$ mlr --json put -S '


 @x = splitnv(substr($Name,1,-1),"-"); $f_nams = @x[1]; $age = @x[2]; $title = @x[3]; $l_name = @x[4]


 ' then reorder -e -f job file.json


{ "Name": "%Hana-29-Mrs-Smith", "f_nams": "Hana", "age": 29, "title": "Mrs", "l_name": "Smith", "job": "engineer" }


{ "Name": "%Mike-31-Mr-Larry", "f_nams": "Mike", "age": 31, "title": "Mr", "l_name": "Larry", "job": "marketing" }


{ "Name": "%Jhon-40-Mr-Doe", "f_nams": "Jhon", "age": 40, "title": "Mr", "l_name": "Doe", "job": "engineer" }




答案2:


#!/usr/bin/env python3


import json


import sys



with open(sys.argv[1]) as json_file:


 for line in json_file:


 json_obj = dict(json.loads(line))


 tokens = json_obj["Name"].split('-')


 extra_data = { 


 "f_nams": tokens[0].replace('%','') ,


 "age" : tokens[1],


 "title" : tokens[2],


 "l_name": tokens[3]


 }


 joined_data = {**json_obj, **extra_data}


 print(json.dumps(joined_data))




它的工作方式是使用上下文管理器open()打开文件,并在完成时自动关闭,

所有这些都转换为json对象,并在标准输出上打印,如果你确实需要将它保存到新文件,请使用shell重定向,如下所示 ./parse_data.py ./data.json > ./new_data.json 或者你想在屏幕上同时看到它 ./parse_data.py ./data.json | tee ./new_data.json

操作方式:


$ ./parse_data.py ./data.json 


{"Name": "%Hana-29-Mrs-Smith", "job": "engineer", "f_nams": "Hana", "age": "29", "title": "Mrs", "l_name": "Smith"}


{"Name": "%Mike-31-Mr-Larry", "job": "marketing", "f_nams": "Mike", "age": "31", "title": "Mr", "l_name": "Larry"}


{"Name": "%Jhon-40-Mr-Doe", "job": "engineer", "f_nams": "Jhon", "age": "40", "title": "Mr", "l_name": "Doe"}



$ cat ./data.json 


{"Name" :"%Hana-29-Mrs-Smith","job":"engineer"}


{"Name" :"%Mike-31-Mr-Larry","job":"marketing"}


{"Name" :"%Jhon-40-Mr-Doe","job":"engineer"}





COM  文件  COMM  对象  Comma  KEY  
相关文章