0

I have file with similar input :

lin1,line2,line3
lin1,line2,line3
lin1,line2,line4

and need convert it to JSON with Python. For example, output should be like this:

{
    "localport_starts_from": 1080,
    "config": [
        {
            "1": "lin1",
            "2": "line2",
            "3": "line3"
        },
        {
            "1": "lin1",
            "2": "line2",
            "3": "line3"
        },
        {
            "1": "lin1",
            "2": "line2",
            "3": "line3"
        }
    ]
}

I have never worked with the json library, so can you show me an example of how to make this?

3
  • You are not showing us your whole input. Where does "localport_starts_from": 1080, come from? How are we to know that your input belongs in an array called "config"? Should the last line of the 3rd dict in "config" actually be "3": "line4" according to your example input? Why are the dict keys "1", "2", and "3" in quotes - shouldn't they be ints? Please edit your question and add as many details as possible. Finally, please look over the documentation for json to familiarize yourself with the module. Commented Apr 9, 2015 at 21:35
  • this not change ""localport_starts_from": 1080" Commented Apr 9, 2015 at 21:53
  • We'll need code to go much further, but don't sweat the json part. Construct a python dict with the content you wnat then use json.dumps to jsonize the whole thing wit ha single call. Commented Apr 9, 2015 at 21:54

1 Answer 1

1

Use the csv module to parse the input and the json to dump the parsing.

with open(input_file) as f:
    rows = list(csv.reader(f))

# rows will be a list of lists, where each inner list contains the values formerly separated by commas
# e.g. [["lin1", "line2", "line3"], ...]

# enumerate(row, 1) returns a generator of [(1, "lin1"), (2, "line2")...]
row_dicts = [{str(i): v for i, v in enumerate(row, 1)} for row in rows]

# now gather the rest of your stuff into a dict
# ....

result_dict["config"] = row_dicts

with open(output_file, 'w') as f:
     json.dump(result_dict, f)
Sign up to request clarification or add additional context in comments.

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.