-2

I have JSON file which has array of 500 objects that looks like this:

{
  "books":[
    {
      "title":"Title 1",
      "year":"2012",
      "authors":"Jack ; George",
      },
    {
      "title":"Title 2",
      "year":"2010",
      "authors":"Leonard ; Robin",
      },
    ...

How can i loop through this file in js or python and change "authors" of every object to look like this:

"authors":["Jack" , "George"]

Thank you.

nikola203
  • 3
  • 2

4 Answers4

1

You need just to split your authors by ;. Call also trim on each author to remove the extra spaces.

const books = [
    {
      "title":"Title 1",
      "year":"2012",
      "authors":"Jack ; George",
    },
    {
      "title":"Title 2",
      "year":"2010",
      "authors":"Leonard ; Robin",
    }
];

books.forEach(item =>  {
   item.authors = item.authors.split(';')
                              .map(author => author.trim());
});

console.log(books);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

I think this code snippet should do the needful.

var obj = {
  "books":[
    {
      "title":"Title 1",
      "year":"2012",
      "authors":"Jack ; George",
      },
    {
      "title":"Title 2",
      "year":"2010",
      "authors":"Leonard ; Robin",
      }]
  };
for(var i in Object.keys(obj.books)){
  obj.books[i].authors = obj.books[i].authors.split(" ; ")
  


}
one.whoknocks
  • 58
  • 1
  • 7
0

If your using python, you can try this:

data = {
    "books":[
      {
       "title":"Title 1",
       "year":"2012",
       "authors":"Jack ; George",
      },
      {
       "title":"Title 2",
       "year":"2010",
       "authors":"Leonard ; Robin",
      }
    ]
   }

for k1 in data:
    for k2 in data[k1]:
        k2['authors'] = [x.strip() for x in k2['authors'].split(';')]

print(data)

Which Outputs:

{'books': [{'title': 'Title 1', 'year': '2012', 'authors': ['Jack', 'George']}, {'title': 'Title 2', 'year': '2010', 'authors': ['Leonard', 'Robin']}]}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
0

Try this:-

for i in a["books"]:
    i['authors'] = [x.strip() for x in (i['authors'].split(";"))]
print(a)  #your output
Narendra
  • 1,511
  • 1
  • 10
  • 20