0

I have a URL with JSON encoded parameters:

http://host/endpoint?cart%5B4887%5D=3&cart%5B2576%5D=2&cart%5B2519%5D=4

After using unquote(request.url) (Flask), I got:

http://host/endpoint?cart[4887]=3&cart[2576]=2&cart[2519]=4

This URL comes from a .php function of WordPress plugin. The reason to use GET with URL parameters instead of POST is because I need to send data to an external API by my plugin without touching / modifying any existing files in WordPress. In the existing files in WordPress, the .php file has specified what wp endpoint to post in .

$cart_items_arr = array("4887"=>3, "2576"=>2, "2519"=4);
$url = add_query_arg( array("cart" => $cart_items_arr), URL);

The output that I want to extract from the URL is

{
  "4887": 3,
  "2576": 2,
  "2519": 4
}

What would be the neat and tidy way to convert a string to dictionary like this?

2
  • 3
    Those are not JSON-encoded parameters. Commented Jun 27, 2019 at 15:22
  • 1
    Where does your URL string comes from? Commented Jun 27, 2019 at 15:42

2 Answers 2

1

You could use potentially use regex to get you most of the way:

import re
str = 'http://host/endpoint?cart[4887]=3&cart[2576]=2&cart[2519]=4'
re.findall("\[(\d+)\]=(\d+)", str) # [('4887', '3'), ('2576', '2'), ('2519', '4')]

You should be able to easily map that into the dictionary you need.

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

Comments

1

Looks cart is consistent, then you can just use a loop to strip them:

{k.strip('cart[]'): v for k, v in request.args.items()}

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.