1

I need to get data from a json page and convert it to a list.

import json
import requests

j = requests.get('http://www.example.com/Portals/0/StaticData/data.js')
abc = json.loads(j.content)

However, error occurred

ValueError: No JSON object could be decoded

what I need is

mylist = ['AALI','ABBA','ABDA'.......]
mylist1 = ['Astra Agro Lestari Tbk','Mahaka Media Tbk','Asuransi Bina Dana Arta Tbk',.......]
1

1 Answer 1

2

You don't have a valid JSON returned, you can clean it up before reading it in with json module:

js = j.content.decode("utf-8").split("=")[-1].strip().strip(';')

json.loads(js)

#[{'code': 'AALI', 'name': 'Astra Agro Lestari Tbk'},
# {'code': 'ABBA', 'name': 'Mahaka Media Tbk'},
# {'code': 'ABDA', 'name': 'Asuransi Bina Dana Arta Tbk'},
# {'code': 'ABMM', 'name': 'ABM Investama Tbk'},
# {'code': 'ACES', 'name': 'Ace Hardware Indonesia Tbk'},
# ...

To unpack the result into two lists:

mylist, mylist1 = zip(*((d['code'], d['name']) for d in json.loads(js)))
Sign up to request clarification or add additional context in comments.

1 Comment

It works, but still have 'u' in the mylist and mylist1. Also, can you add explanation for js = j.content.decode("utf-8").split("=")[-1].strip().strip(';') and json.loads(js)?

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.