5

I am uploading one JS file using HTML input file tag. I am reading the data in Python. Since in my data var acb_messages is written, I am not able to parse it. And I want to use this variable name to get the data so I can remove it.

var acb_messages = {"messages": [{
    "timestamp": 1475565742761,
    "datetime": "2016-10-04 12:52:22 GMT+05:30",
    "number": "VM-449700",
    "id": 1276,
    "text": "Some text here",
    "mms": false,
    "sender": false
    }
]}

How can I parse it in Python and then how can I use it?

Patrick Yoder
  • 1,065
  • 4
  • 14
  • 19
TARUN KHANEJA
  • 71
  • 1
  • 1
  • 2

3 Answers3

8

Two approaches that I would try if I were at your place -

  1. Convert my .js file to .json file and then using method suggested by @Sandeep Lade.

  2. Reading .js file as string, cropping out the value part and then using json.loads(<cropped part>) as suggested by @rahul mr.

Here is how to achieve 2nd solution -

import json

with open('your_js_file.js') as dataFile:
    data = dataFile.read()
    obj = data[data.find('{') : data.rfind('}')+1]
    jsonObj = json.loads(obj)

What's happening here is that you are finding first reading your .js file (that contains js object that needs to be converted into json) as string, find first occurence of { and last occurence of }, crop that part of string, load it as json.

Hope this is what you are looking for.

Warning - Code works only if your js file contains js object only.

DannyMoshe
  • 6,023
  • 4
  • 31
  • 53
aquaman
  • 1,523
  • 5
  • 20
  • 39
2

The options above are correct, but the JSON syntax in JS can be a little different than in Python:

example.js:

property.docs = {
    messages: {
    timestamp: 1475565742761,
    datetime: "2016-10-04 12:52:22 GMT+05:30",
    number: "VM-449700",
    id: 1276,
    text: "Some text here",
    mms: false,
    sender: false
}
};

Therefore we need one more tweak that I found at: How to convert raw javascript object to python dictionary?

The complete code should be:

import json
import demjson

with open('example.js') as dataFile:
    data = dataFile.read()
    json_out = data[data.find('{'): data.rfind('}')+1]
    json_decode = demjson.decode(json_out)

print(json_decode)
-1
import json
jsonfile=open("/path/to/json file")
data=json.load(jsonfile)

the above code will store will store your json data in a dictionary called data. You can then process the dictionary

Sandeep Lade
  • 1,865
  • 2
  • 13
  • 23