Specifying the Contents of a json File

Asked 1 years ago, Updated 1 years ago, 68 views

The contents of the json file are:

{
  "version": 1.2,
  "people": [
    {
      "pose_keypoints_2d": [
        570.599,
        272.875,
        ...,
        292.453,
        0.616146
      ],
      "face_keypoints_2d": [
        416.352,
        227.967,
        ...,
        213.009,
        0.822855
      ],
      "hand_left_keypoints_2d": [ ],
      "hand_right_keypoints_2d": [ ],
      "pose_keypoints_3d": [ ],
      "face_keypoints_3d": [ ],
      "hand_left_keypoints_3d": [ ],
      "hand_right_keypoints_3d": [ ]
    }
  ]
}

I would like to specify face_keypoints_2d" for this kind of content, but I get an error.
I think the cause was probably the first [and last] and I could read it well after deleting that part.
Is there any way to specify the contents without deleting this part?

python python3 json

2022-09-30 19:35

1 Answers

If the error is TypeError: list indications must be integrators or slices, not str,
The reason is expected to be that the first [and last] contains an array of "people" but is not accessed as an array.

You can get "face_keypoints_2d" without rewriting json with the sample code below.
The print statement in the sample code states j["people"][0]["face_keypoints_2d"] to access the beginning of the "people" array.

import json
# Unnecessary items in json are omitted
s='{"version": 1.2, "people": [{"pose_keypoints_2d": [570.599, 272.875, 0.719388, 0.616146],
"face_keypoints_2d": [416.352, 227.967, 0.822855],
"hand_right_keypoints_3d": [ ]}} ' '
j = json.loads(s)
print(j["people"][0]["face_keypoints_2d"])
# [416.352, ...] is printed

About additional questions in comments

When loading a file, read json.loads to json.load by referring to the answers to similar question.
json.loads takes the json string and json.load takes the file path as arguments, respectively.

If you use read as read_data=f.read(), the read_data contains a string type.
The following exceptions occur when read_data['people'] is written for string type instead of json type:

TypeError: string indications must be integrators

Sample file loading code:

import json
with open("test.json", "r") as f:
    j = json.load(f)
    print(j['people'][0]['face_keypoints_2d'])

If you write down the code that can reproduce the error and the specific error content, it will be easier to get an accurate answer.

When you add a question in a comment, the questions are scattered throughout the page and the indentation of the code is broken, making it difficult to read.
Also, it may be difficult for anyone other than the respondents to answer the comment, so we recommend that you edit the question statement or post a new question as another question.


2022-09-30 19:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.