3

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?

asked Jan 19, 2019 at 19:55
2
  • Who selects the arrays to be serialised? Commented Jan 19, 2019 at 19:59
  • Can you please let me know? This affects the answer you get. When should the filtering be done? Before or during serialisation? I am not sure. Or is this just an example, and you want all rows with indices in this manner? Commented Jan 19, 2019 at 20:15

4 Answers 4

3

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]]
iz_
16.7k4 gold badges28 silver badges43 bronze badges
answered Jan 19, 2019 at 20:10

2 Comments

When I try and serialise that I get an error message - TypeError: Object of type 'int64' is not JSON serializable - I am assuming it is because it is numypy values instead of python int
@fightstarr20 , you're right. I believe solution with pd.DataFrame is better, but if you want to make this work you need to wrap x and y in int(x) and int(y).
2

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.

answered Jan 19, 2019 at 20:03

Comments

2

pandas presents a convenient solution:

import pandas as pd
import numpy as np
df=pd.DataFrame(myarray, columns=["x", "y"])
df["Section"]=df.index
df.to_json(orient="records")

this yields:

 '[{"x":148,"y":362,"Section":0},{"x":153,"y":403,"Section":1},
{"x":163,"y":443,"Section":2},{"x":172,"y":483,"Section":3},
{"x":186,"y":521,"Section":4},{"x":210,"y":553,"Section":5},
{"x":239,"y":581,"Section":6},{"x":273,"y":604,"Section":7},
{"x":314,"y":611,"Section":8},{"x":353,"y":602,"Section":9}]'

The solution is a little bit different, but you can easily find your way in pure python to convert it into your structure.

answered Jan 19, 2019 at 20:52

Comments

0

I needed something similar but for a more general case. This replaces any numpy ndarray in a python dict, list, set or any mix of them recursively either in place or should return a numpyified copy.

from copy import deepcopy
import numpy as np
def unnumpyify(something, inplace=False):
 if inplace:
 new_something = something
 else:
 new_something = deepcopy(something)
 if type(new_something) == np.ndarray:
 new_something = new_something.tolist()
 if type(new_something) == dict:
 for k in new_something:
 if type(new_something[k]) == np.ndarray:
 new_something[k] = new_something[k].tolist()
 if type(new_something[k]) == dict:
 new_something[k] = unnumpyify(new_something[k])
 elif type(new_something[k]) == list:
 new_something[k] = unnumpyify(new_something[k])
 elif type(new_something) == list:
 for i,k in enumerate(new_something):
 if type(k) == np.ndarray:
 new_something[i] = k.tolist()
 if type(k) == dict:
 new_something[i] = unnumpyify(k)
 elif type(k) == list:
 new_something[i] = unnumpyify(k)
 elif type(new_something) == set:
 for k in new_something:
 if type(k) == np.ndarray:
 new_something.remove(k)
 new_k = k.tolist()
 new_something.add(new_k)
 if type(k) == dict:
 new_something.remove(k)
 new_k = unnumpyify(k)
 new_something.add(new_k)
 elif type(k) == list:
 new_something.remove(k)
 new_k = unnumpyify(k)
 new_something.add(new_k)
 return new_something
answered Mar 30, 2022 at 8:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.