Python converting string into json object - python

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

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

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.

Related

Is it possible to convert unquoted JSON to either CSV or appropriate JSON format using pyspark

I am using pyspark in which I am extacting the required string from log files which is a JSON string but without the quotes. Below is the example:
{PlatformVersion=123,PlatformClient=html,namespace=NAT}
I want to convert it to either CSV or JSON as I want to further store it into relation DB using data pipelines. Is there a way to achieve converting such string to CSV or JSON?
The below is doing the job.
Steps:
remove curly braces
split by ,
split by =
populate the dict with key & value
result = {}
log_line = '{PlatformVersion=123,PlatformClient=html,namespace=NAT}'
log_line = log_line[1:-1]
parts = log_line.split(',')
for part in parts:
k,v = part.split('=')
result[k] = v
print(result)
output
{'PlatformVersion': '123', 'PlatformClient': 'html', 'namespace': 'NAT'}

How to retrieve key value pair within listed dictionary in python?

I have a list of dictionaries as a key value pairs, where I want to access the data of each dict by key:
sample data:
['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"',...
real data
>>> data
['"imageUrl":"/images/products/klein/04047122_k.jpg"', '"art":"04047122"', '"productId":"170336"'; } } }) ']
This unfortunatelly does not work:
re.findall(r'(?:number\(\{)(.*)', data)[0].split(',')
How can I retrieve the values by name e.g. data['number'] ?
For a more robust solution, since each string in the input list is a valid line of CSV, delimited by a colon, you can use csv.reader to parse the list and then pass the resulting sequence of key-value pairs to the dict constructor to build a dict:
import csv
lst = ['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"']
data = dict(csv.reader(lst, delimiter=':'))
You can then access data['number'] as desired.
Try to convert your data to a real dictionary:
data = ['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"']
data_dict = dict([x.replace('"','').split(":") for x in data])
and then you will be able to access your keys:
print(data_dict["number"]) # output: 04047122
You can convert your string list to an actual dictionary easily:
>>> ls = ['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"']
>>> data = dict(elem.replace('"', '').split(':') for elem in ls)
>>> data
{'imageUrl': '/images/4.jpg', 'number': '04047122', 'name': 'test'}
>>> data['number']
'04047122'

How to convert list into json format in python [duplicate]

This question already has answers here:
How to convert a list of numbers to jsonarray in Python
(2 answers)
Closed 3 years ago.
x=json.dumps(result)
print(x)
Output:
['Client Name:'Sriram',
'Trade Date :'03-09-2019',
'Security :CERAMICIST-ICICLE,NAT CO - PHARMA',
'Quantity:14,2',
'Net Rate: 145.7500,552.3725',
'Buy/Sell :'Buy ', 'Buy',
'Net Total:2040.5000,1104.7450']
and I want to convert this list into a json format like this:
{'Client Name': Sriram',
'Trade Date' :03-09-2019',
'Security' :['CERAMICIST-ICICLE','NAT CO - PHARMA',
'Quantity':'14,2',
'Net Rate':['145.7500','552.3725'],
'Buy/Sell':['Buy','Sell',
'Net Total':['2040.5000','1104.7450']
As I have mentioned in comment, your result is not a valid JSON.
Let me have these assumption:
You have a list of string, and for each string it is in form of key : value
You want a JSON string like
{ "key1" : "value1",
"key2" : "value2",...}
(i.e. all key and values are string)
You could just construct a dict, with each line in the list become an entry of dict, and then use json.dumps.
If you need to preserve the type of the value (e.g. 123 should be a number instead of string: "key1" : 123), then it is more complicated: you may need to check the format of the value and convert it to correct type
Another choice is, as key: value is a valid entry in YAML (note the missing double quote and the space after colon), you can do simple massaging in your message and construct a yaml string, use yaml parser to parse it to a dict, and then use json parser to construct a json string. Something like:
import yaml
import json
l = [ "a:b", "c: 123", "d: true"]
result = json.dumps(
yaml.load("\n".join(
[ t[0] + ": " + t[1] for t in
[ s.split(":", 1) for s in l]
])))
# result string is '{"a": "b", "c": 123, "d": true}'
One Liner in Python using dict comprehension. We need to first convert it in dict using dict comprehension and then use json.dumps() to convert it to json format.
li = ['TradeDate :03-09-2019',
'Security :ICICIPRAMCICICI500',
'Quantity :14',
'NetSale: 145.7500',
'Buy/Sell :2040.5000BuyINF109KC1CZ3']
di = {i.split(':')[0]:i.split(':')[1] for i in li}
print(di)
js = json.dumps(di)
print(js)
Outputs:
{'TradeDate ': '03-09-2019', 'Security ': 'ICICIPRAMCICICI500', 'Quantity ': '14', 'NetSale': ' 145.7500', 'Buy/Sell ': '2040.5000BuyINF109KC1CZ3'}
{"TradeDate ": "03-09-2019", "Security ": "ICICIPRAMCICICI500", "Quantity ": "14", "NetSale": " 145.7500", "Buy/Sell ": "2040.5000BuyINF109KC1CZ3"}

Python list formatting with JSON

I'm a newbie in Python trying to turn information from an Excel file into JSON output.
I'm trying to parse this Python list:
value = ['Position: Backstab, Gouge,', 'SumPosition: DoubleParse, Pineapple']
into this JSON format:
"value": [
{
"Position": [
"Backstab, Gouge,"
]
},
{
"SumPosition": [
"DoubleParse, Pineapple"
]
}
]
Please note:
This list was previously a string:
value = 'Position: Backstab, Gouge, SumPosition: DoubleParse, Pineapple'
Which I turned into a list by using re.split().
I've already turned the string into a list by using re.split, but I still can't turn the inside of the string into a dict, and the value from the dict into a list.
Is that even possible? Is it the case to format the list/string with JSON or previously prepare the string itself so it can receive the json.dump method?
Thanks in advance!
You can iterate over the list to achieve desired result.
d = {'value': []}
for val in value:
k, v = val.split(':')
tmp = {k.strip() : [v.strip()]}
d['value'].append(tmp)
print(d)
{'value': [{'Position': ['Backstab, Gouge,']},
{'SumPosition': ['DoubleParse, Pineapple']}]}
Here is a quick way.
value = ['Position: Backstab, Gouge,',
'SumPosition: DoubleParse, Pineapple']
dictionary_result = {}
for line in value:
key, vals = line.split(':')
vals = vals.split(',')
dictionary_result[key] = vals
Remaining tasks for you: trim off empty strings from result lists like [' Backstab', ' Gouge', ''], and actually convert the data from a Python dict to a JSON file

multiple json dictionaries python

I have a json file with multiple json dictionaries:
the format is as following
{"x":"1", "y":"2", "z": "3"}{"x": "2","y":"3", "z":"4"}{"x":"3", "y":"4", "z":"5"}
How can I convert this to one json dictionary format as following:
{"items":[{"x":"1", "y":"2", "z": "3"},{"x": "2","y":"3", "z":"4"},{"x":"3", "y":"4", "z":"5"}]}
Already mostly answered here: Importing wrongly concatenated JSONs in python
That shows you how to pick up each JSON element from a concatenated list of them (which is not valid JSON) using json.JSONDecoder method raw_decode(). The rest is a simple matter of concatenating strings '{"items":[', element1, ",", element2, ... "]" or alternatively, accumulating them as a list, wrapping that with a one-item dict and if required, dumping that json as a string with json.dumps
OK expanding on that
import json
d = json.JSONDecoder()
# get your concatenated json into x, for example maybe
x = open('myfile.json','r').read()
jlist=[]
while True:
try:
j,n = d.raw_decode(x)
jlist.append(j)
except ValueError:
break
x=x[n:]
# my original thought was
result = '{"items":[' +
','.join( [ str(s) for s in jlist] ) +
']'
# but this is neater
result = json.dumps( { "items":jlist })
# and of course if you want it for programmatic use, just
result_as_json = dict( items=jlist )

Categories

Resources