1
{
  "result" : [{
      "conf" : 1.000000,
      "end" : 0.300000,
      "start" : 0.000000,
      "word" : "bright"
    }, {
      "conf" : 1.000000,
      "end" : 0.720000,
      "start" : 0.330000,
      "word" : "bright"
    }, {
      "conf" : 1.000000,
      "end" : 1.950000,
      "start" : 1.710000,
      "word" : "bright"
    }],
  "text" : "bright bright bright"
}

I have this JSON array with me. I need to extract all the details from the "result" in the table format. For example,

   conf       start      end        word
1.000000    0.000000   0.300000    bright
1.000000    0.330000   0.720000    bright
1.000000    1.710000   1.950000    bright

How can I extract these values from the "result" part and append the details in excel?

3 Answers 3

2

Using csv built-in module.

import csv

json = {
  "result" : [{
      "conf" : 1.000000,
      "end" : 0.300000,
      "start" : 0.000000,
      "word" : "bright"
    }, {
      "conf" : 1.000000,
      "end" : 0.720000,
      "start" : 0.330000,
      "word" : "bright"
    }, {
      "conf" : 1.000000,
      "end" : 1.950000,
      "start" : 1.710000,
      "word" : "bright"
    }],
  "text" : "bright bright bright"
}

header = json['result'][0].keys()
with open('results.csv', 'w', newline='') as file_:
    dict_writer = csv.DictWriter(file_, fieldnames=header)
    dict_writer.writeheader()
    dict_writer.writerows(json['result'])
Sign up to request clarification or add additional context in comments.

Comments

1
import pandas as pd

json_val = {
  "result" : [{
      "conf" : 1.000000,
      "end" : 0.300000,
      "start" : 0.000000,
      "word" : "bright"
    }, {
      "conf" : 1.000000,
      "end" : 0.720000,
      "start" : 0.330000,
      "word" : "bright"
    }, {
      "conf" : 1.000000,
      "end" : 1.950000,
      "start" : 1.710000,
      "word" : "bright"
    }],
  "text" : "bright bright bright"
}
pd.read_json(json_val['result'], orient='index').to_csv('someName.csv')

1 Comment

I am getting an error here "TypeError: string indices must be integers". How should I solve this?
0

I would very much recommend pandas, will not take a lot of lines.

Based on your example, this is achievable with:

import pandas as pd
pd.read_json(json['result'], orient='index').to_excel('output.xlsx') 

See documentation on how to create a dataset from a dictionary and how to export to Excel.

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.