Reputation: 41
I need to split a string at a '.' and everything after is irrelevant I just need the first element at index[0].
I have tried using the .split('.')[0] in a for loop however, the output never changes.
The text.txt file looks like this [{"description":"large", "istrue":"yes","name":"george.doe.jane", "clear":"true", "money": 5000}] It has more than one object but they are all built the same.
output_file = open ('text.txt', 'r')
json_array = json.load(output_file)
json_list = []
for item in json_array:
name = "name"
money = "money"
json_items = {name:None, money:None}
json_items[name.split('.')[0]] = item[name.split('.')[0]]
json_items[money] = item[money]
json_list.append(json_items)
The output currently looks like {'name': 'george.doe.jane', 'money':5000} I would like it to look like {'name': 'george','doe','jane', 'money':5000}
Upvotes: 1
Views: 46
Reputation: 295
I think you're just using .split()
wrong: fair enough. Here's an example of its usage:
s = 'h.e.l.l.o'
a = s.split('.')
# ['h', 'e', 'l', 'l', 'o']
So your for
loop maybe should look a bit more like:
for i in json_array:
json_list.append({'name': i['name'].split('.'), 'money': i['money']})
output should be
json_list = [{'name': ['george', 'doe', 'jane'], 'money': 5000}]
Upvotes: 0
Reputation: 20500
You can use with
context manager to open your file, and split the name on .
to create the list of names
import json
#Open the file
with open ('text.txt', 'r') as output_file:
#Load the json array
json_array = json.load(output_file)
#Iterate through the list and append the resultant dictionary to the list
json_list = [{'name': item['name'].split('.'), 'money': item['money']} for item in json_array]
print(json_list)
The output will be
[{'name': ['george', 'doe', 'jane'], 'money': 5000}]
Upvotes: 1