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
Related
Is there anyway i can find the position of object by its key in Json file. I tried with the collection module but seems not to work with data from the json file even though its dictionary
reda.json file
[{"carl": "33"}, {"break": "55"}, {"user": "heake"}, ]
import json
import collections
json_data = json.load(open('reda.json'))
if type(json_data) is dict:
json_data = [json_data]
d = collections.OrderedDict((json_data))
h = tuple(d.keys()).index('break')
print(h)
Also tried this
j = 'break'
for i in json_data:
if j in i:
print(j.index('break'))
Result is 0
``
You can use enumerate to generate indices for a sequence:
json_data = [{"carl": "33"}, {"break": "55"}, {"user": "heake"}]
key = 'break'
for index, record in enumerate(json_data):
if key in record:
print(index)
This outputs: 1
You don't require collections for this. Simply use list comprehension to generate a list and then get the index.
Here's my code:
import json
json_data = json.load(open('reda.json'))
json_key_index = [key for key in json_data]
print(json_key_index.index("break"))
Also, looking at your reda.json the format doesn't seem pretty well-versed. I recommend changing the reda.json to:
{
"carl": "33",
"break": "55",
"user": "heake"
}
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'
I have a quick question. I have a list in Python with the values.
service_list = [ AX100 , BX200 , CX300 ]
Now I am trying to pass this list to a sample JSON body where I can get a SNOW ticket opened so this is the Sample JSON data:
'u_template': 'CONFIG FILE',
'approval': 'Request for Approval',
'u_uuid': 'a13b8180-6400-11e8-a39e-005046a6000d',
'short_description': 'short_description_ie ',
'start_date': '2018-06-11 05:00:55',
'end_date': '2018-06-12 05:00:55',
'work_start': '2018-06-11 05:00:55',
'work_end': '2018-06-12 05:00:55',
'u_creating_group': 'sdo',
'u_affected_ci': service_list
}
But for the key u_affected_ci it is expecting the value to be only AX100 , BX200 , CX300 and not [ AX100 , BX200 , CX300 ], so please suggest me ideas how to remove the [ in front and ] at the back of the list add " " to cover the entire value and then pass to JSON body.
Replace the list with a ,-delimited string.
d = {
...,
'u_affected_ci': ','.join(service_list)
}
data = json.dumps(d)
It looks like the JSON requires a string rather than a list. Instead of thinking of this as removing the [] from the list (which represents an array in JSON), you need to figure out how to convert your list into a string with the correct format. In particular, the string must be comma delimited. Thankfully we have the join() method on strings. It works like this:
> service_list = [ 'AX100' , 'BX200' , 'CX300' ]
> ','.join(service_list)
=> 'AX100,BX200,CX300'
If you store the result in a variable, you can use that variable in the dictionary that you will serialize to JSON:
service_string = ','.join(service_list)
I am trying to output the following JSON from my python (2.7) script:
[
{
"id": "1002-00001",
"name": "Name 1"
},
{
"id": "1002-00002",
"display": "Name 2"
},
]
What data structure in Python will output this when using json.dumps?
The outermost item is a python list, but what should be the type of items inside the list? It looks like a dictionary with no keys?
Hopefully this clarifies the notes in comments that are not clear for you. It's achieved by appending (in this case small) dictionaries into a list.
import json
#Added an extra entry with an integer type. Doesn't have to be string.
full_list = [['1002-00001', 'Name 1'],
['1002-00002', 'Name 2'],
['1002-00003', 2]]
output_list = []
for item in full_list:
sub_dict = {}
sub_dict['id'] = item[0] # key-value pair defined
sub_dict['name'] = item[1]
output_list.append(sub_dict) # Just put the mini dictionary into a list
# See Python data structure
print output_list
# Specifically using json.dumps as requested in question.
# Automatically adds double quotes to strings for json formatting in printed
# output but keeps ints (unquoted)
json_object = json.dumps(output_list)
print json_object
# Writing to a file
with open('SO_jsonout.json', 'w') as outfile:
json.dump(output_list, outfile)
# What I think you are confused about with the "keys" is achieved with an
# outer dictionary (but isn't necessary to make a valid data structure, just
# one that you might be more used to seeing)
outer_dict = {}
outer_dict['so_called_missing_key'] = output_list
print outer_dict
I have JSON data as an array of dictionaries which comes as the request payload.
[
{ "Field1": 1, "Feld2": "5" },
{ "Field1": 3, "Feld2": "6" }
]
I tried ijson.items(f, '') which yields the entire JSON object as one single item. Is there a way I can iterate the items inside the array one by one using ijson?
Here is the sample code I tried which is yielding the JSON as one single object.
f = open("metadatam1.json")
objs = ijson.items(f, '')
for o in objs:
print str(o) + "\n"
[{'Feld2': u'5', 'Field1': 1}, {'Feld2': u'6', 'Field1': 3}]
I'm not very familiar with ijson, but reading some of its code it looks like calling items with a prefix of "item" should work to get the items of the array, rather than the top-level object:
for item in ijson.items(f, "item"):
# do stuff with the item dict