Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cleaner way of manipulating string to JSON

I have the following invalid JSON string which I’d like to convert into valid JSON (so each "template" will have a vuln-x key before it):

{"template":"network/vsftpd-detection.yaml","matcher-status":true}{"template":"cves/2018/CVE-2018-15473.yaml","matcher-status":true}{"template":"cves/2016/CVE-2016-6210.yaml","matcher-status":true}

I’m currently doing the following in order to format it:

import json

s1 = '{"template":"network/vsftpd-detection.yaml","matcher-status":true}{"template":"cves/2018/CVE-2018-15473.yaml","matcher-status":true}{"template":"cves/2016/CVE-2016-6210.yaml","matcher-status":true}'

s2 = s1.split('{"template":')
num = s1.count('{"template":')
out_json = "{"

for x in range(num):
        out_json += '"vuln-' + str(x) + '":{"template":' + s2[x+1]

new_json = out_json.replace("true}", "true},")
cleaned_json = new_json[:-1] + "}"

print(cleaned_json)

I feel this is incredibly messy and am sure there’s a cleaner way to do it – any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s the desired output which I’m getting with my current script:

{
   "vuln-0":{
      "template":"network/vsftpd-detection.yaml",
      "matcher-status":true
   },
   "vuln-1":{
      "template":"cves/2018/CVE-2018-15473.yaml",
      "matcher-status":true
   },
   "vuln-2":{
      "template":"cves/2016/CVE-2016-6210.yaml",
      "matcher-status":true
   }
}

>Solution :

Add a delimiter between the dictionaries to enable easier splitting, then process as dictionaries:

import json

s = '{"template":"network/vsftpd-detection.yaml","matcher-status":true}{"template":"cves/2018/CVE-2018-15473.yaml","matcher-status":true}{"template":"cves/2016/CVE-2016-6210.yaml","matcher-status":true}'

# add a delimiter not used in the string (nul) and split on it.
strings = s.replace('}{', '}\0{').split('\0')

# dict comprehension
data = {f'vuln-{i}': json.loads(v) for i, v in enumerate(strings)}

print(json.dumps(data, indent=2))

Output:

{
  "vuln-0": {
    "template": "network/vsftpd-detection.yaml",
    "matcher-status": true
  },
  "vuln-1": {
    "template": "cves/2018/CVE-2018-15473.yaml",
    "matcher-status": true
  },
  "vuln-2": {
    "template": "cves/2016/CVE-2016-6210.yaml",
    "matcher-status": true
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading