#๐Ÿ”’ Parse JS-stringified JSON

33 messages ยท Page 1 of 1 (latest)

quasi parcelBOT
#

@round rune

Python help channel opened

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.

solid sparrow
#

Your original message got deleted

round rune
#

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

solid sparrow
#

U can maybe try the json module in python

round rune
#

Doesn't work

hard sable
#

Use ast.literal_eval to get the string from its stringified representation

#

then pass that to json.loads

round rune
hard sable
#

It appears to just work for me. Can you show your code?

#

Also, that's a Python syntax error. How?

round rune
#

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

gray veldt
#

!paste

quasi parcelBOT
#
Pasting large amounts of code

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.

gray veldt
#

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

hard sable
#

Also, you can't close someone else's thread, I'm pretty sure.

gray veldt
#

Then Use Regex

hard sable
#

It's already been solved before you. The correct solution is to use something that can parse string literal representations, like ast.literal_eval.

gray veldt
#

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)

quasi parcelBOT
#
Python help channel closed

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.