Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Convert numpy array to JSON

I have a Python numpy array called myarray that looks like this..

[[148 362]
 [153 403]
 [163 443]
 [172 483]
 [186 521]
 [210 553]
 [239 581]
 [273 604]
 [314 611]
 [353 602]]

I want to create JSON that looks like this..

myjson = [
    {'section': '3',
     'x': '163',
     'y': '362',
    },
    {'section': '7',
     'x': '239',
     'y': '581',
    },
    {'section': '10',
     'x': '353',
     'y': '602',
    },
]

This represents the 3rd, 7th and 10th line in the original numpy array. Does anybody have an example of something similar being achieved?


2 Answers

To add on to Andrii's answer, I believe you can also unpack the arrays like this to make it slightly cleaner:

[{'section': i+1, 'x': x, 'y': y} for i, [x, y] in enumerate(myarray) if i in [2, 6, 9]]
like image 68
jacob Avatar answered Sep 14 '26 22:09

jacob


If your input array is arr I believe you want something like:

[{'section': i+1, 'x': x[0], 'y': x[1]} for i, x in enumerate(arr) if i in [2, 6, 9]]

[2, 6, 9] are your [3, 7, 10] positions, only starting from 0.

like image 42
andnik Avatar answered Sep 14 '26 20:09

andnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!