0

I have a pretty weird JSON string from which I need specific values saved in a .txt file.

The string looks like this:

{"available":[{"place":"abc","stock":3},{"place":"abcd","stock":5}]}

So I need to extract the "place" and "stock" into a list. So the result should look like this:

abc 3
abcd 5

I tried it with:

with open("available.txt", "w") as f:
  for i in list['available']:
    f.write(I['place'] + ['stock'] + '\n')

But it won't work. I think its because the "stock" value does not have any "". Is it possible to do what I want with Python?

4
  • str(i['stock']) ? Commented Oct 5, 2020 at 13:22
  • it won't work because you're creating a list with the string stock. you're forgetting to look up the key in i["stock"] Commented Oct 5, 2020 at 13:22
  • Although, it won't get that far because I is undefined first. Commented Oct 5, 2020 at 13:23
  • I think if you review how iterators work you should be good, can see that you're trying to get it to come together but just missing a few things Commented Oct 5, 2020 at 13:36

2 Answers 2

1

It should be

with open("available.txt", "w") as f:
  for i in list['available']:
    f.write(i['place'] + " " + str(i['stock']) + '\n')

You can also use format, to make it a bit simpler

with open("available.txt", "w") as f:
  for i in list['available']:
    f.write("{0} {1}\n".format(i["place"],str(i["stock"])))
Sign up to request clarification or add additional context in comments.

Comments

0

Try the below:

data = {"available":[{"place":"abc","stock":3},{"place":"abcd","stock":5}]}

with open("available.txt", "w") as f:
    for d in data['available']:
        f.write(d['place'] + " " + str(d['stock']) + '\n')
        print (d['place'], d['stock'])

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.