Home > Mobile >  Cleaner way of manipulating string to JSON
Cleaner way of manipulating string to JSON

Time:02-11

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?

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
   }
}

CodePudding user response:

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
  }
}
  • Related