如何将一个 JSON 中的图像属性替换为另一个 JSON 中的图像属性?

发布于 2025-01-15 12:35:13 字数 1908 浏览 2 评论 0原文

我正在尝试从一组 json 文件复制图像字段并替换另一组 JSON 文件中的图像字段。

我从中提取的 JSON 文件结构:

[
    {
        "\ufeffFile Name": "16.png",
        "image": "https://arweave.net/v8OOGgKmlAZF56bpGQRv1nM691gu2FMlrNK3KY-3HZk"
    }
]

我需要替换的 JSON 文件结构:

{
  "name": "name",
  "symbol": "KK",
  "description": "description",
  "seller_fee_basis_points": 1000,
  "image": "image.png",
  "external_url": "https://www.image.net",
  "edition": 16,
}

代码:

import json
import os



def getFileImage(fp):
    with open(fp, 'r') as ff:
        try:
            return json.load(ff)['image']
        except:
            return None



def ReadAndReplace(filename, image):
    with open(filename, 'r') as ff:
        try:
            data = json.load(ff)
            data['image'] = image
            return json.dumps(data, indent = 4)
        except:
            print(f'Could not process file {filename}')
            return None



def Save(filename, data):
    with open(filename, 'w') as ff:
        ff.write(data)



def EnsureOutput():
    if not os.path.exists('output'):
        os.mkdir('output')

    if not os.path.exists('input') or not os.path.exists('toReplace'):
        print('Please create "input" and "toReplace" folders')
        exit()


def main():
    EnsureOutput()

    for i in os.listdir('toReplace'):
        filepath1 = os.path.join('input', i)
        filepath2 = os.path.join('toReplace', i)
        outpath = os.path.join('output', i)

    if os.path.exists(filepath1):
        image = getFileImage(filepath1)
        data = ReadAndReplace(filepath2, image)
        Save(outpath, data)
    else:
        print(f'No input file for toReplace "{i}" was found')



main()

当我运行此代码时,图像字段更新为 NULL 而不是我需要的链接。

I am attempting to copy the image field from one group of json files and replace the image field in another group of JSON files.

JSON file structure that I am pulling from:

[
    {
        "\ufeffFile Name": "16.png",
        "image": "https://arweave.net/v8OOGgKmlAZF56bpGQRv1nM691gu2FMlrNK3KY-3HZk"
    }
]

JSON file structure that I need to replace:

{
  "name": "name",
  "symbol": "KK",
  "description": "description",
  "seller_fee_basis_points": 1000,
  "image": "image.png",
  "external_url": "https://www.image.net",
  "edition": 16,
}

Code:

import json
import os



def getFileImage(fp):
    with open(fp, 'r') as ff:
        try:
            return json.load(ff)['image']
        except:
            return None



def ReadAndReplace(filename, image):
    with open(filename, 'r') as ff:
        try:
            data = json.load(ff)
            data['image'] = image
            return json.dumps(data, indent = 4)
        except:
            print(f'Could not process file {filename}')
            return None



def Save(filename, data):
    with open(filename, 'w') as ff:
        ff.write(data)



def EnsureOutput():
    if not os.path.exists('output'):
        os.mkdir('output')

    if not os.path.exists('input') or not os.path.exists('toReplace'):
        print('Please create "input" and "toReplace" folders')
        exit()


def main():
    EnsureOutput()

    for i in os.listdir('toReplace'):
        filepath1 = os.path.join('input', i)
        filepath2 = os.path.join('toReplace', i)
        outpath = os.path.join('output', i)

    if os.path.exists(filepath1):
        image = getFileImage(filepath1)
        data = ReadAndReplace(filepath2, image)
        Save(outpath, data)
    else:
        print(f'No input file for toReplace "{i}" was found')



main()

When I run this code the image field updates to NULL instead of the link I need.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莫言歌 2025-01-22 12:35:13

您正在加载的输入是一个 JSON 数组,因此被解析为一个 python 列表,您显然无法像您尝试那样通过键访问它。
您首先需要访问数组中的对象,然后可以使用键访问该对象。

请参阅以下内容:

input = """
[
    {
        "\ufeffFile Name": "16.png",
        "image": "https://arweave.net/v8OOGgKmlAZF56bpGQRv1nM691gu2FMlrNK3KY-3HZk"
    }
]
"""

input_parsed = json.loads(input)
print(type(input_parsed))
print(input_parsed[0]["image"])

预期输出:

<class 'list'>
https://arweave.net/v8OOGgKmlAZF56bpGQRv1nM691gu2FMlrNK3KY-3HZk

对于您的 ReadAndReplace() 函数,这将如下所示:

def read_and_replace(filename, image):
    with open(filename, 'r') as ff:
        try:
            # data is a list
            data = json.load(ff)
            # be sure the list has actually one value exactly
            if len(data) == 1:
                data[0]['image'] = image
            return json.dumps(data, indent=4)
        except (json.JSONDecodeError, KeyError):
            print(f'Could not process file {filename}')
            return None

The input you are loading is a JSON array and hence parsed as a python list, which you can obviously not access by keys as you are trying to do.
You first need to access the object within the array and then you may access this object with keys.

See the following:

input = """
[
    {
        "\ufeffFile Name": "16.png",
        "image": "https://arweave.net/v8OOGgKmlAZF56bpGQRv1nM691gu2FMlrNK3KY-3HZk"
    }
]
"""

input_parsed = json.loads(input)
print(type(input_parsed))
print(input_parsed[0]["image"])

Expected output:

<class 'list'>
https://arweave.net/v8OOGgKmlAZF56bpGQRv1nM691gu2FMlrNK3KY-3HZk

For your ReadAndReplace() function this would look like this:

def read_and_replace(filename, image):
    with open(filename, 'r') as ff:
        try:
            # data is a list
            data = json.load(ff)
            # be sure the list has actually one value exactly
            if len(data) == 1:
                data[0]['image'] = image
            return json.dumps(data, indent=4)
        except (json.JSONDecodeError, KeyError):
            print(f'Could not process file {filename}')
            return None
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文