Home > front end >  Converting string with new lines into json array
Converting string with new lines into json array

Time:09-26

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?

CodePudding user response:

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

CodePudding user response:

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'}
  • Related