0

Есть у меня файл json. В нем хранится массив props. У каждого prop'a есть строка isKinematic, и она везде ровна false. Мне нужно сделать так что бы все isKinematic были ровны true при помощи python, и библиотеки json

Вот код json

{
      "name": "Windows_9",
      "uniqueId": 201.025131,
      "position": {
        "x": 4.61797333,
        "y": 0.500008941,
        "z": 13.395874
      },
      "rotation": {
        "x": 6.405395E-05,
        "y": 1.0,
        "z": 0.000102993377,
        "w": 5.44786453E-05
      },
      "isKinematic": false,
      "instantiationData": null,
      "runtimeData": null
    },
    {
      "name": "Wall2_10",
      "uniqueId": 297.653931,
      "position": {
        "x": -2.69872737,
        "y": 0.499172926,
        "z": 17.0329571
      },
      "rotation": {
        "x": 0.000120101235,
        "y": -6.43402927E-06,
        "z": 2.06660843E-05,
        "w": 1.0
      },
      "isKinematic": false,
      "instantiationData": null,
      "runtimeData": null
    },
    {
      "name": "Windows_9",
      "uniqueId": 278.69635,
      "position": {
        "x": -10.0158234,
        "y": 0.4994458,
        "z": 13.3465414
      },
      "rotation": {
        "x": 1.15973666E-08,
        "y": 0.7071068,
        "z": -5.241425E-08,
        "w": 0.7071067
      },
      "isKinematic": false,
      "instantiationData": null,
      "runtimeData": null
    },
    {
      "name": "Windows_9",
      "uniqueId": 52.42003,
      "position": {
        "x": 4.64777946,
        "y": 0.500144958,
        "z": 5.52883625
      },
      "rotation": {
        "x": 0.000135970971,
        "y": 0.707417846,
        "z": -3.817615E-06,
        "w": -0.706795633
      },
      "isKinematic": false,
      "instantiationData": null,
      "runtimeData": null
    }

Сложности возникли на моменте try except

import json
import os

if not os.path.exists("/storage/emulated/0/Hypper_Maps"):
 os.mkdir("/storage/emulated/0/Hypper_Maps")
 
imap = input("map name: ")
map = f"{imap}"+".svn"

try:
    
    path = f"/storage/emulated/0/Hypper_Maps/{map}"
except FileNotFoundError:
        print(f"Can not find {map} in /storage/emulated/0/Hypper_Maps")


print("Commands: Freeze, unfreeze")
freezed = input("Command: ")

with open(path,"r") as osave:
 mapData = json.loads(osave.read())
 
for prop in mapData["props"]:
 if freezed == "Unfreeze":
     prop["isKinematic"] = False
 if freezed == "Freeze":
     prop["isKinematic"] = True

with open(path, 'w') as save:
 json.dump(mapData, save)
 osave.close()

Проблема состоит в том, что даже если название файла не верное, он проходит блоки try except

7
  • С чем возникли сложности?
    – insolor
    31 мар в 15:25
  • Там не нужен try-except. Добавьте свой код, мы подскажем что с ним не так.
    – insolor
    31 мар в 16:24
  • imap = input("map name: ") map = f"{imap}"+".svn" try: path = f"/storage/emulated/0/Hypper_Maps/{map}" except FileNotFoundError: print(f"Can not find {map} in /storage/emulated/0/Hypper_Maps") По какой то причине игнорируется блок try except 31 мар в 16:25
  • Код вставьте в сам вопрос.
    – insolor
    31 мар в 16:25
  • Блоки игнорируются 31 мар в 16:27

1 ответ 1

1

Используем библиотеку json, считываем в data, проходимся по всем элементам массива и изменяем isKinematic на true

import json

with open('your_file.json', 'r') as f:
    data = json.load(f)

for prop in data:
    prop['isKinematic'] = True

with open('your_file.json', 'w') as f:
    json.dump(data, f)

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.