1

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}

5
  • The text.txt file looks like this [{'description':'large', 'istrue':'yes','name':'jane.doe', 'clear':'true', 'money': 5000}] It has more than one object but they are all built the same. Commented Jul 11, 2019 at 15:51
  • Do I need to append instead of read? Commented Jul 11, 2019 at 15:54
  • It was double quotes. Commented Jul 11, 2019 at 16:03
  • I'm sorry, new to python. Is an embedded dictionary the proper syntax? Commented Jul 11, 2019 at 16:07
  • I have updated the question. I just need the output split. Commented Jul 11, 2019 at 16:18

2 Answers 2

1

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}]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.