0

how can i convert from this json-format:

{
   "Key1": {
       "Value": "123",
       "Value": "456",
   },
   "Key2" : {
       "Value": "789",
   },
   "Key3": {
       "Value": "000",
   },
   "Key4" : {
       "Value": "111",
   }
}

to this csv-format:

     |Col A|Col B|Col C|Col D|Col E|
Row 1|123  |456  |789  |000  |111  |

I want to ignore the keys and just add the values to the csv and all values should be in one row...I don´t need any headers or index. just the values

2
  • 5
    That's not valid JSON. You can't have identical keys in a dict. Commented Jan 26, 2022 at 14:02
  • StackOverflow is not a free coding service. You're expected to try to solve the problem first, and show your code. Please update your question to show what you have already tried in a minimal reproducible example. For further information, see How to Ask, and take the tour. Commented Jan 26, 2022 at 14:16

1 Answer 1

2

Assuming that the JSON is fixed to be valid, then you can easily do this with a nested list comprehension:

data = {
    "Key1": {
        "Value1": "123", # Note: I've fixed your JSON here.
        "Value2": "456",
    },
    "Key2": {
        "Value1": "789",
    },
    "Key3": {
        "Value1": "000",
    },
    "Key4": {
        "Value1": "111",
    },
}
# In practice this might be in a different data.json file,
# which can then be opened with:

# import json
# with open("data.json", "r") as f:
#     data  = json.load(f)

# Take the values of the outer dict, and then the values of the inner dict
values = [value for value_dict in data.values() for value in value_dict.values()]
print(values)

# Write to a file by separating with commas
with open("values.csv", "w") as f:
    f.write(",".join(values))

This outputs

['123', '456', '789', '000', '111']

and values.csv becomes:

123,456,789,000,111
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much. i was spending the whole day for that and couldnt find any solution here. TY

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.