简体   繁体   中英

How do I turn certain rows in a csv column into a JSON format?

I have certain rows in a child column formatted like this

{ "label ": "Apple", "id ": 2, "dataType ": "Fruit "}]

The issue I have is that since the child column is empty in couple of rows, but gets populated like this in some other rows, I wanted to see if I could turn this into a JSON object and see if I can do operations like that, but that doesn't seem possible as I keep getting an error saying

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I think that is because the "id ": 2, there is no "2" in the 2. How can I replace an empty value like that 2 and turn it into "2", so it is a proper JSON format?

Also is it possible for me to like maybe extract the label, id, and dataType and make them their own heading on a different exported csv file? for example, let's say my input.csv file is like this

Value, Children:
1,"label ": "Banana", "id ": 11, "dataType ": "Fruits "
2,
3, "label ": "Shoes ", "id ": 1150, "dataType ": "Accesories "

I want the outputted file to look like this:

label, id, dataType,

Banana, 11, Fruits

Shoes, 1150, Accesories

Is this possible?

EDIT: The original dataset actually contains multiple values of

{"label": "val1", "id":2, "dataType": "value", "label": "val2", "id":3, "dataType": "value3"}

in the same row, inside of one cell there can be multiple of this values defined, can I still make them into column headings and store values in the associated column's?

Say your column is:

column = pd.Series(
    [{"label ": "Banana", "id ": 11, "dataType ": "Fruits "},
     {},
     {"label ": "Shoes ", "id ": 1150, "dataType ": "Accesories "}]
)

You can convert this column to a dataframe by pd.json_normalize :

new_df = pd.json_normalize(column)

And then save it in the format you like (eg, csv):

new_df.to_csv('file_name.csv', index=False)

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM