very strange Json need to be formatting

Question:

i got a json feed like this:

{'OUT': '232827@@@Price;1=9.8=0;2=4.1=1;3=7.9=0;#Needs;1=3.0=0;2=1.4=1;3=3.5=0;'}

it is very strange format:

  1. Without KEYS
  2. Used "=" to be separators
  3. Two sets of data in one json array
  4. With a prefix at the begginning(i am not sure the "OUT" isn’t the prefix? maybe)

I want the output result like this with indicated Key:

The First Json:

{
  "No":1,
  "Price":9.8,
  "status":0
},
{
  "No":2,
  "Price":4.1,
  "status":1
},
{
  "No":3,
  "Price":7.9,
  "status":0
}

The Second Json (After"#Needs"):

{
  "No":1,
  "Needs":3.0,
  "status":0
},
{
  "No":2,
  "Needs":1.4,
  "status":1
},
{
  "No":3,
  "Needs":3.5,
  "status":0
}
Asked By: Kelvin Yeung

||

Answers:

A regex will handle that nicely

import re

value = {'OUT': '232827@@@Price;1=9.8=0;2=4.1=1;3=7.9=0;#Needs;1=3.0=0;2=1.4=1;3=3.5=0;'}

result = []
for part in value['OUT'].split("Needs"):
    subresult = []
    for a, b, c in re.findall(r"(d+)=([d.]+)=(d+)", part):
        subresult.append({
            "No": int(a),
            "Needs": float(b),
            "status": int(c)
        })
    result.append(subresult)

print(result)

[[{'No': 1, 'Needs': 9.8, 'status': 0}, {'No': 2, 'Needs': 4.1, 'status': 1}, {'No': 3, 'Needs': 7.9, 'status': 0}],
 [{'No': 1, 'Needs': 3.0, 'status': 0}, {'No': 2, 'Needs': 1.4, 'status': 1}, {'No': 3, 'Needs': 3.5, 'status': 0}]]
Answered By: azro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.