简体   繁体   中英

convert text file contain data in key value format to json

Lets say I have a text file contain data like

[ key = 1542633482511430199, value=>>>BasicData:isConfirmAndOrder=0,brmRequestId=BR-2018-0000124,requestType=batch,projectName=Automation_Product_By_Admin,projectId=PRJ-2018-0000477,department=Global Packaging] 

How can I convert that to json format.

I prefer if i can get solution in javascript however language is not a constraint.

In order to do this you will need to do a lot of replaces, a helper function will help you:

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

Now, let's do the replaces and run JSON.parse :

    JSON.parse(
'[ key = 1542633482511430199, value=>>>BasicData:isConfirmAndOrder=0,brmRequestId=BR-2018-0000124,requestType=batch,projectName=Automation_Product_By_Admin,projectId=PRJ-2018-0000477,department=Global Packaging]'
.replace(':', ':{').replace(']', '}}')
.replace(':', ':{').replaceAll("=", ':"')
.replaceAll(",", '",')
.replace(':"', ":")
.replace('[', '{')
.replace("}}", '"}}}')
.replace('",', ",")
.replace('>>>', '{')
.replace('{{', '{')
.replace('value:"', "value:")
.replace("=", ":")
.replace('key :', '"key" :')
.replace('value:', '"value":')
.replace('BasicData:', '"BasicData":')
.replace('isConfirmAndOrder:', '"isConfirmAndOrder":')
.replace('brmRequestId:', '"brmRequestId":')
.replace('requestType:', '"requestType":')
.replace('projectName:', '"projectName":')
.replace('projectId:', '"projectId":')
.replace('department:', '"department":')
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM