Shwetha K
Shwetha K

Reputation: 37

TypeError: string indices must be integers. when try access the json variables

Please help me with this.

This is my json file: abc.json

{
  "name": "abc",
  "id": 123,
  "header": "timestamp id name"
}

In python script when i try to access the json variable like col_names = data['header'] and print the data into csv file. But i get the error now as TypeError: string indices must be integers.

Please can anyone help me with this. It would be very greateful. Thank you.

Upvotes: 0

Views: 67

Answers (2)

Barbaros Özhan
Barbaros Özhan

Reputation: 65373

You might use ast.literal_eval in order to write values of header key only such as

import json
import ast

with open('abc.json') as f, open('abc.csv', 'w') as f_out:
    data = ast.literal_eval(f.read())
    for i in range(0,len(data)):
        val = data[i]['header']
        f_out.write(''.join(format(val))+ '\n')

Upvotes: 1

Satarupa
Satarupa

Reputation: 78

import json

f = open('data.json')

data = json.load(f)

print(data['header'])

Upvotes: 1

Related Questions