Ramesh K
Ramesh K

Reputation: 302

Python converting string into json object

Output is

"Passanger status:\n passanger cfg086d96 is unknown\n\n"

i want to convert this into json object like

{
  "Passanger_status": "passanger cfg086d96 is unknown"
}

Upvotes: 0

Views: 4874

Answers (2)

Akshay Kathpal
Akshay Kathpal

Reputation: 445

You can try this one also

data_dic = dict()
data = "Passanger status:\n passanger cfg086d96 is unknown\n\n"
x1 , x2 = map(str,data.split(":"))
data_dic[x1] = x2
print data_dic

If you find it simple

Output :

{'Passanger status': '\n passanger cfg086d96 is unknown\n\n'}

and for space to underscore you can use replace method in keys of the dictionary.

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

just apply json.dumps() to this native python dictionary composed in one-line:

{k.replace(" ","_"):v.strip() for k,v in (x.split(":") for x in ["Passanger status:\n passanger cfg086d96 is unknown\n\n"])}

the inner generator comprehension avoids to call split for each part of the dict key/value. The value is stripped to remove trailing/leading blank spaces. The space characters in the key are replaced by underscores.

result is (as dict):

{'Passanger status': 'passanger cfg086d96 is unknown'}

as json string using indent to generate newlines:

>>> print(json.dumps({k.replace(" ","_"):v.strip() for k,v in (x.split(":") for x in ["Passanger status:\n passanger cfg086d96 is unknown\n\n"])},indent=2))
{
  "Passanger_status": "passanger cfg086d96 is unknown"
}

Upvotes: 2

Related Questions