0

I'm attempting to get multiple items from an array but it returns an error however if I get just one it does not. My code:

stockjson = json.loads(stockinfo.text)
test1 = stockjson['variation_list'][0]['test1']
print(test1)

Stockinfo:

{"id":"TestID","availability_status":"NOT_AVAILABLE","variation_list":[{"sku":"TEST1","availability":0,"availability_status":"NOT_AVAILABLE","test1":"test1"},[{"sku":"TEST2","availability":0,"availability_status":"NOT_AVAILABLE","test1":"test2"},

I would like to get the result of every test1 but if I take [0] out of my code I get:

    test1 = stockjson['variation_list']['test1']
TypeError: list indices must be integers or slices, not str

I'd also like to find the SKU and the test1 for each section (not sure what to call it) thanks for any help provided

Ogden
  • 477
  • 1
  • 8
  • 21
  • 2
    `test1 = [d['test1'] for d in stockjson['variation_list']]` should do it. – hilberts_drinking_problem May 05 '18 at 19:37
  • Thanks @YakymPirozhenko, however it prints the full array at the start then after each item in the array is there anyway to stop it printing the full array at the start? – Ogden May 05 '18 at 19:39
  • 1
    You will get more and better answers if you create a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example. Especially make sure that the input and expected test data are complete (not pseudo-data), and can be easily cut and and paste into an editor to allow testing proposed solutions. – Stephen Rauch May 05 '18 at 19:40
  • 1
    You may want to look at using a JSONPath, dpath, KVC, or similar library, that lets you specify things like this with calls like `path(stockjson, 'variation_list.*.test1')`. There are a lot of options, and I don't know which ones to recommend, but you can [search PyPI](https://pypi.org/search/?q=jsonpath), or maybe go to the Community section on python.org and find a mailing list or IRC channel to ask for recommendations on. – abarnert May 05 '18 at 19:47
  • Updated post with another question – Ogden May 05 '18 at 19:50
  • @Ogden Don't do that; create a new question. – abarnert May 05 '18 at 19:54

0 Answers0