0

I have the following string(with new lines after each value): " value1 value2 value3 " I need to convert it to a json array(using python) in the following format:

{"keywords": [{"keyword": "value1"},{"keyword": "value2"},{"keyword": "value3"}]}

I tried all kinds of methods, always resulting in invalid json. Any suggestions?

2 Answers 2

1

Split the string into an array, map it to a dictionary of keyword:line, and convert it into json.

import json

def map_line(line):
    return {"keyword": line}
    
lines = "value1\nvalue2\nvalue3".split("\n")
    
result = json.dumps({"keywords": list(map(map_line, lines))})
Sign up to request clarification or add additional context in comments.

Comments

1
import json
sample_data = '{"keywords": [{"keyword": "value1"},{"keyword": "value2"},{"keyword": "value3"}]}'
for idx, key in enumerate(json.loads(sample_data)):
    for idx2, key2 in enumerate(json.loads(sample_data)[key]):
        print(key2)

Output:

{'keyword': 'value1'}
{'keyword': 'value2'}
{'keyword': 'value3'}

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.