#๐ Parse JS-stringified JSON
33 messages ยท Page 1 of 1 (latest)
@round rune
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Your original message got deleted
Sigh
Basically, I have this file that I need to parse in JS. How do I parse the string into a Python object?
Here's the file
I can use removeprefix and removesuffix to get rid of window.APP_BOOTSTRAP = and the ending ;
But how do I actually parse the JS stringified object
U can maybe try the json module in python
Doesn't work
Use ast.literal_eval to get the string from its stringified representation
then pass that to json.loads
I actually tried that, but it throws SyntaxError: unexpected character after line continuation character
It appears to just work for me. Can you show your code?
Also, that's a Python syntax error. How?
Just a second
Ohh
Found the error
I was stripping the " from the string ends
For literal_eval to work, I needed to retain that
Fixed
Thanks
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Bro here's the fix:
https://paste.pythondiscord.com/VAGA
What I did ๐ฟ:
I copied all the code to vscode, searched for backslash, replace all backslashes with empty string and formatted the file. Here's your coffee โ.
!close
They wanted a general way to deal with input like this. Manually doing the replacement in a text editor doesn't cut it.
Also, you can't close someone else's thread, I'm pretty sure.
Then Use Regex
It's already been solved before you. The correct solution is to use something that can parse string literal representations, like ast.literal_eval.
The only problem for me is that lets the interpreter know that # exists in the string. But it detects it as a comment and I don't want to escape the string of my own because the algorithm should be dynamic (my style of writing)
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.