0

I processed a data in python and saved the file in JSON format.

However, I ran into a problem after getting the JSON file when I use them in node.js which is

the JSON file looks like as below.

{
    "title": "Christmas Eggnog",
    "ingredients": "['whites', 'yolks', 'sugar', 'rye', 'whiskey', 'brandy', 'rum', 'cream']",
    "id": "05zEpbSqcs9E0rcnCJWyZ9OgdH0MLby"
},

The ingredients has to be a normal array however, it is an array held by quotation marks. And it eventually makes it impossible to read this json file as intended.

{
    "title": "Christmas Eggnog",
    "ingredients": ["whites", "yolks", "sugar", "rye", "whiskey", "brandy", "rum", "cream"],
    "id": "05zEpbSqcs9E0rcnCJWyZ9OgdH0MLby"
},

I would like to get the log value like below. When I read this JSON file in node.

const fs = require('fs');

let predata = fs.readFileSync('./data/testonce.json')
let data = JSON.parse(predata)
let newData = [];
data.forEach((d) => {
    newData.push((d) => {
        let targetarray = d.ingredients.split(',')
        return {...d, ingredients: targetarray }
    })
})

console.log(newData[0])
//"whites"

I can't get the string "white" because node doesn't understand the fact that "['whites', 'yolks', 'sugar', 'rye', 'whiskey', 'brandy', 'rum', 'cream']" is an array. Node sees it as one long string.

How do I turn this string into a normal array?

Edit)

My python code is as below.

import pandas as pd

df = pd.read_csv('./test.csv')

ingredients = df['ingredients']

for i in range(len(ingredients)):
    ingredients[i]=str(ingredients[i])[1:-1]

ingredients

df['ingredients']=ingredients

df.to_csv ('./datatest.csv', index = False, header=True)

After this, I used csv->json formatter in this website. https://csvjson.com/[![enter image description here]1]1

Edit)

this is the csv file link

we.tl/t-Kw435qpNNd

It looks like thisenter image description here

Edit) Sample csv text This is the sample csv text.

title,ingredients,id Christmas Eggnog ,"['whites', 'yolks', 'sugar', 'rye', 'whiskey', 'brandy', 'rum', 'cream']",05zEpbSqcs9E0rcnCJWyZ9OgdH0MLby "Veal, Carrot and Chestnut Ragoût ","['chestnuts', 'veal', 'stew', 'meat', 'oil', 'onion', 'garlic', 'leaf', 'salt', 'chicken broth', 'wine', 'carrots', 'sage']",mF5SZmoqxF4WtIlhLRvzuKk.z6s7P2S Caramelized Bread Pudding with Chocolate and Cinnamon ,"['butter', 'brioche', 'quality', 'bread', 'crusts', 'eggs', 'egg', 'yolks', 'brown', 'sugar', 'cream', 'milk', 'vanilla', 'cinnamon', 'nutmeg', 'kosher salt', 'chocolate', 'top']",oQV5D7cVbCFwmrDs3pBUv2y.AG0WV26 Sherried Stilton and Green Peppercorn Spread ,"['stilton', 'cream cheese', 'peppercorns', 'brine', 'sherry']",Z9seBJWaB5NkSp4DQHDnCAUBTwov/1u Almond-Chocolate Macaroons ,"['almonds', 'sugar', 'cinnamon', 'salt', 'egg', 'almond', 'semisweet', 'chocolate']",bB3GxoAplVZeoX3fzWNWyeECtQFxw6G White Sauce or Bechamel Sauce ,"['butter', 'flour', 'milk', 'salt', 'pepper']",FHQAJvovVtPyKWlzgFEHgSUJsCM2Tjq

12
  • 1
    please add the python code that produces the json Commented Mar 8, 2021 at 7:34
  • Does this answer your question? How to convert an Object {} to an Array [] of key-value pairs in JavaScript Commented Mar 8, 2021 at 7:35
  • 4
    The real problem is in the code that created this 'faulty' JSON, so this is the part to correct. Commented Mar 8, 2021 at 7:35
  • @LelioFaieta No... Commented Mar 8, 2021 at 7:43
  • @KrishnaChaurasia I added my python code thank you Commented Mar 8, 2021 at 7:45

3 Answers 3

2

because its a string, you need to strip of the bad bits you do not want, and then convert what is left of the string into an array

var list = "['whites', 'yolks', 'sugar', 'rye', 'whiskey', 'brandy', 'rum', 'cream']".replace(/[\[\]["',]/g,'').split(" ");

The replace uses regex to remove the " ' , [ ] characters, and the split cuts up the string by the remaining spaces and converts it into an array.

console.log(list);
0: "whites"
1: "yolks"
2: "sugar"
3: "rye"
4: "whiskey"
5: "brandy"
6: "rum"
7: "cream"
length: 8
__proto__: Array(0)
Sign up to request clarification or add additional context in comments.

Comments

0

I agree with Thierry Lathuille to fix the problem in the producer. If you you want to patch it up here, I would parse the string as JSON and just replace it:

data.forEach(r => {
    r.ingredients = JSON.parse(r.ingredients);
}

Comments

0

const json = {
    "title": "Christmas Eggnog",
    "ingredients": "['whites', 'yolks', 'sugar', 'rye', 'whiskey', 'brandy', 'rum', 'cream']",
    "id": "05zEpbSqcs9E0rcnCJWyZ9OgdH0MLby"
}

const ingredients = json.ingredients.substr(1, json.ingredients.length -2)
const ingredientsList = ingredients.split(', ').map(item => item.substr(1, item.length -2))



console.log(ingredientsList)

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.