5

I am uploading one js file using html input file tag. And 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
    }
]}

pls help how to parse it in python and how to use it

Van Peer
  • 2,057
  • 2
  • 22
  • 34
TARUN KHANEJA
  • 71
  • 1
  • 1
  • 2

3 Answers3

6

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
  • 5,068
  • 3
  • 23
  • 43
aquaman
  • 1,377
  • 4
  • 16
  • 34
1

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,794
  • 2
  • 12
  • 22