Home > other >  Swap 2 lines within a JSON file. Lat and Lon without tags
Swap 2 lines within a JSON file. Lat and Lon without tags

Time:02-19

I have a large json file with code that looks a lot like below. I wish to have the same output but need the latitude and longitude swapped.

"path": [
        [
            -0.662301763628716,
            51.48792441079866
        ],
        [
            -0.661955225774188,
            51.487855733392
        ],
        [
            -0.66143913564835,
            51.48772120562989
        ]

The goal is to swap these 2 numbers around, they vary as they are GPS latitude and longitude values. Any solution using progams/language script is welcome.

CodePudding user response:

Say your json looked like:

j = {"path": [
        [
            -0.662301763628716,
            51.48792441079866
        ],
        [
            -0.661955225774188,
            51.487855733392
        ],
        [
            -0.66143913564835,
            51.48772120562989
        ]]}

You can reverse each list in place:

from typing import List

def reverse(l: List):
    l.reverse()

and apply it to the json in place:

map(reverse, j["path"])

And now the json looks like:

{'path': [[51.48792441079866, -0.662301763628716], [51.487855733392, -0.661955225774188], [51.48772120562989, -0.66143913564835]]}

p.s. I don't like doing stuff in place, but its the way the .reverse function works...

CodePudding user response:

Iterate through and just swap them by their index.

data = {"path": [
        [
            -0.662301763628716,
            51.48792441079866
        ],
        [
            -0.661955225774188,
            51.487855733392
        ],
        [
            -0.66143913564835,
            51.48772120562989
        ]]}

dataSwap = {'path':[]}
for x in data['path']:
    dataSwap['path'].append([x[-1], x[0]])
  • Related