Y
Y
youwereneverreallyhere2021-10-29 06:57:39
JSON
youwereneverreallyhere, 2021-10-29 06:57:39

How to find and replace part of a value in a json file?

I have this JSON in a file:

[
  {
    "id": 0,
    "type": "Left",
    "count": 3,
    "accessories": {
      "aa": "V S B",
      "bf": "H",
      "dc": "P E"
    }
  },
  {
    "id": 1,
    "type": "Right",
    "count": 2,
    "accessories": {
      "qw": "L",
      "bm": "K L"
    }
  },
...
]


Which has over 5000 objects. How can I parse JSON and extract its values?
Expected result for JSON file:

[
  {
    "name": "Name #0",
    "attributes": [
      {
        "trait_type": "accessory",
        "value": "V S B"
      },
      {
        "trait_type": "accessory",
        "value": "H"
      },
      {
        "trait_type": "accessory",
        "value": "P E"
      },
      {
        "trait_type": "type",
        "value": "Left"
      }
    ]
  },
...
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2021-10-29
@youwereneverreallyhere

Read, sort, change, write.
Or the question is how to change the structure from one to another?
Option:

const data = [
  {
    id: 0,
    type: 'Left',
    count: 3,
    accessories: {
      aa: 'V S B',
      bf: 'H',
      dc: 'P E',
    },
  },
  {
    id: 1,
    type: 'Right',
    count: 2,
    accessories: {
      qw: 'L',
      bm: 'K L',
    },
  },
];

const newData = data.map((item) => ({
  name: `Name #${item.id}`,
  attributes: Object.values(item.accessories).map((accessory) => ({
    trait_type: 'accessory',
    value: accessory,
  })).concat([{
    trait_type: 'type',
    value: item.type,
  }]),
}));

console.log(newData);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question