L
L
Lovky2017-10-06 22:10:18
Python
Lovky, 2017-10-06 22:10:18

How to partially write JSON to CSV in python?

I need to get JSON and write only two fields from it to the file. the djon itself of the form {"a" : 1, "b" : 2, "c" : 3}. I need, for example, only a and c.
You can first truncate the JSON itself after receiving it, I understood how, but since this operation will be performed many times, then most likely the method is very resource-intensive compared to partial recording, if there is one.
I get it like this:
url = "any.address"
data = requests.get(url=url)
binary = data.content
output = json.loads(binary)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Dugin, 2017-10-10
@Lovky

Practical example. Sorry, that the picture is inconvenient to copy:59dcd5d04c079796802083.png

A
Alexey Cheremisin, 2017-10-06
@leahch

What doesn't fit?

a = output["a"]
c = output["c"]

S
Sly_tom_cat ., 2017-10-07
@Sly_tom_cat

You got a dictionary (dict) with values ​​in the output.
If you know what to remove (and that it's always there) and there isn't much of it, then just del(output["a"]) ... and keep the truncated output.
If you need to delete a lot, but you need to save nothing, then it's easier to pull out the desired a = output["a"] and save it.
If you need to delete / pull out several elements, then do the methods described above in a loop.
For example:

#удаление
for item in ('a', 'b'):
  del(output[item])


# выборка
result = dict()
for item in ('a', 'b'):
  result[item] = output[item]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question