0

I have some javascript text to parse with python There is in js html elemet such variable:

this.products = ko.observableArray([#here is some json, #here is some json])

observableArray could be an holder for 1 json it will be observableArray({'id': '234234'}) or observableArray(['id': '3123123]), also it can hold infinite number of json per comma like in code pasted higher

how can i get this string with jsons with regexp i have try:

regex = re.compile('\n^(.*?)=(.*?)$|,',)
js_text = re.findall(regex, js)
print(js_text)

but im getting:

File "/usr/lib/python2.7/re.py", line 177, in findall return _compile(pattern, flags).findall(string) TypeError: expected string or buffer

7
  • did you want the id values? Commented Jun 22, 2014 at 11:37
  • "Parsing JS with regex" - DON'T YOU DARE!!! Use a JSON parser instead. Commented Jun 22, 2014 at 11:37
  • did you want regex like this \'id\':\s*\'([0-9]*)\'? Commented Jun 22, 2014 at 11:42
  • What value for js causes the exception? Commented Jun 22, 2014 at 11:44
  • @user3477950 i need to get this string from large js file , then to parse with json Commented Jun 22, 2014 at 11:51

1 Answer 1

1

js is not a string nor a buffer. Are you sure that js is a string (or a buffer)?

# no problem
>>> js = "this.products = ko.observableArray({'id': '234234'})"
>>> js_text = re.findall(regex, js)
>>> print(js_text)
[]

# argument is not a string nor a buffer (in this case None)
>>> js_text = re.findall(regex, None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/mhawke/virtualenvs/urllib3/lib64/python2.7/re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer
>>> js_text = re.findall(regex, js)
>>> print(js_text)
[]

BTW, it's slightly nicer to call regex.findall(js).

And, there is a (different) problem with your regex pattern.

Sign up to request clarification or add additional context in comments.

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.