Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

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}

1 Answer

0 votes
by (25.1k points)

Open the file using the with keyword and split the names . This will create a list of names.

Like this:

import json

with open ('text.txt', 'r') as output_file:

    json_array = json.load(output_file)

    json_list = [{'name': item['name'].split('.'), 'money': item['money']} for item in json_array]

    print(json_list)

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 31, 2019 in Python by Rajesh Malhotra (19.9k points)
0 votes
1 answer

Browse Categories

...