0

I am using an csv to json converter but it messes up my order of objects. I tried different converting-scripts, but they all mess up the order. My csv is ordered like this:

Group-of-Signals name,Group-of-Signals description,Signal name,Signal data type,Signal unit of measurement,Signal description,Signal ID,Signal index

But after the conversion it looks like this:

[{
    "Signal ID": "-1",
    "Group-of-Signals description": "",
    "Signal index": "0",
    "Signal name": "EUVPulseCount",
    "Signal unit of measurement": "M",
    "Signal data type": "SDT_STRING",
    "Signal description": "",
    "Group-of-Signals name": "DPI_0"
}]

I would like to have it like this:

[{
    "Group-of-Signals name" : "DPI_0",
    "Group-of-Signals description" : "",
    "Signal name" : "EUVPulseCount",
    "Signal data type" : "SDT_STRING",
    "Signal unit of measurement" : "M",
    "Signal description" : "",
    "Signal ID" : "-1",
    "Signal index" : "0"
}]

I have included the code over here so it won't be a messy question: https://codeshare.io/B0KyP

I checked the answer that is here: Items in JSON object are out of order using "json.dumps"? but I can't get it to work.

UPDATE: I still don't have it working. All the solutions are about loading a JSON file. In my case I don't load JSON file. I dump data in a new created JSON-file.

Community
  • 1
  • 1
  • Possible duplicate of [Items in JSON object are out of order using "json.dumps"?](http://stackoverflow.com/questions/10844064/items-in-json-object-are-out-of-order-using-json-dumps) – glibdud Oct 10 '16 at 12:20
  • Is there another solution because I can't get it working that way. sort_keys=True works, but I don't want it alphabetical ordered. I want a custom order, which is read out of the csv file because the headers might change – Sebastiaan Speck Oct 10 '16 at 13:01
  • Look at the second example (OrderedDict). – glibdud Oct 10 '16 at 13:03
  • Although note that the order of the elements is being lost in the reading in of the CSV, so you'll need to address it there first. – glibdud Oct 10 '16 at 13:05
  • @glibdud could you help me implementing it? At this moment I have csv_rows.OrderedDict([("Group-of-Signals name"),("Group-of-Signals description"),("Signal name"),("Signal data type"),("Signal unit of measurement"),("Signal description"),("Signal ID"),("Signal index")]) but that doesn't work – Sebastiaan Speck Oct 10 '16 at 13:20

1 Answers1

0

Use OrderedDict:

import csv
import json
from collections import OrderedDict

def whatever(filename):
    r = []
    with open(filename, 'r') as fp:
        reader = csv.reader(fp)
        headers = next(reader)
        for row in reader:
            data = OrderedDict(zip(headers, row))
            r.append(data)
    return json.dumps(r)
Philip Tzou
  • 5,926
  • 2
  • 18
  • 27