0
import requests #package required to handle API requests
import json #built in package to handle JSON 
import os #accesing variables from .bash_profile

i= 0 #const required to iteration of loop

f = open("/mnt/c/_KOD_/project/JSON/output.txt", "a", encoding="UTF-8" ) 

fraza=str
id_category=int

url = os.environ.get("PROD_LB")
print("Provide search phrase :")
input(fraza)
print("provide category:")
input(id_category)
payload = "\r\n{\r\n  \"criteria\": {\r\n    \"product_list.show\": true,\r\n    \"product_list.show_if_below\": -1,\r\n    \"product_list.limit\": -1,\r\n    \"product_sum.show\": true,\r\n    \"query.phrase\": \"", fraza ,"\",\r\n    \"category.id_or_deeper\": [\"", id_category,"diod \"]\r\n  }\r\n}"

headers = {
    'Content-Type': "application/json",
    'User-Agent': "PostmanRuntime/7.18.0",
    'Accept': "*/*",
    'Cache-Control': "no-cache",
    'Postman-Token': "75924d05-2bd0-4133-aed7-515aa644a535,bfdc06e9-6142-4822-a919-81390ba871e4",
    'Host': "search.tme.eu:8443",
    'Accept-Encoding': "gzip, deflate",
    'Content-Length': "230",
    'Connection': "keep-alive",
    'cache-control': "no-cache"
    }

response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)

ress = json.loads(response.text)
list = ress["product_list"]
a = list.__len__() #no longer needed in for loop.

# this part below is quite junky and i have no clue how to revive it...
**For list, value in list.items() : 
# while i < a:
    f.write(list["symbol"])
    f.write("\r\n")
    # i +=1
    f.close** 

Payload above genere JSON response that look like

{
    "request_id": 4454370058,
    "product_list": [
        {
            "score": 19993,
            "symbol": "M22-ES-MS2",
            "id": 346733
        },
.
.
.
        {
            "score": 19989,
            "symbol": "M22-D-R-X0/KC11/I",
            "id": 94432
        }

    ],
    "do_show": true,
    "do_show_list": {
        "do_show_products": true,
        "do_show_parameters": false,
        "do_show_parameter_values": false,
        "do_show_flags": false
    }
}

My goal is to save part of response to txt file that look like:

M22-ES-MS2
M22-D-R-X0/KC11/I

I was able to do this by saving respones to JSON file and from that to save to final format... however that was not optimal.. Currently im stuck with either of 2 errors When i try to do this via While loop im receving :

in _encode_params
    for k, vs in to_key_val_list(data):
ValueError: too many values to unpack (expected 2)

or after reading THIS im stuck with

 File "/mnt/c/_KOD_/project/JSON/request.py", line 39
    For list, value in list.items() : 
           ^
SyntaxError: invalid syntax

As I have no clue how this should work.

This is my most advanced python code I have ever created in my 3 weeks of programming.

Niviral
  • 187
  • 1
  • 4
  • 14

2 Answers2

1

list is a reserved name in python, try changing the name list to something else. You can put key, value instead of list, value. Also the For should be lower case for.

Erindy
  • 155
  • 11
1

you can load the json data using the json library and then just iterate over the products list printing the symbols.

data = """{
    "request_id": 4454370058,
    "product_list": [
        {
            "score": 19993,
            "symbol": "M22-ES-MS2",
            "id": 346733
        },
        {
            "score": 19989,
            "symbol": "M22-D-R-X0/KC11/I",
            "id": 94432
        }

    ],
    "do_show": true,
    "do_show_list": {
        "do_show_products": true,
        "do_show_parameters": false,
        "do_show_parameter_values": false,
        "do_show_flags": false
    }
}"""

import json
json_data = json.loads(data)
for product in json_data['product_list']:
    print(product['symbol'])

OUTPUT

M22-ES-MS2
M22-D-R-X0/KC11/I
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42
  • That ```for``` loop worked but i still got trouble with ```ValueError: too many values to unpack (expected 2)``` when i put 2 variable to payload. Thank you. – Niviral Oct 21 '19 at 11:58
  • What do you mean? – Chris Doyle Oct 21 '19 at 12:07
  • When i put to payload ```payload = """\r\n{\r\n \"criteria\": {\r\n \"product_list.show\": true,\r\n \"product_list.show_if_below\": -1,\r\n \"product_list.limit\": -1,\r\n \"product_sum.show\": true,\r\n \"query.phrase\": \"""",fraza,"""\",\r\n \"category.id_or_deeper\": [\"""",id_category,"""\"]\r\n }\r\n}"""``` variables "fraza" and "id_category" using input i got ```ValueError: too many values to unpack (expected 2)``` There is no issue when i put the same input as part of payload string without variable – Niviral Oct 21 '19 at 12:10
  • that payload isnt valid json – Chris Doyle Oct 21 '19 at 13:39