简体   繁体   中英

How to extract some data from a json file

I would like to extract some data from a json file and insert it into another json file like this:

  {
    "name": "File",
    "artist": "Andrew",
    "attributes": 
[
      {
        "trait_type": "Background",
        "value": "Black"
      },
      {
        "trait_type": "Base",
        "value": "White"
      },
      {
        "trait_type": "Eye Type",
        "value": "Eye"
      },
      {
        "trait_type": "Ear Type",
        "value": "Ear"
      },
      {
        "trait_type": "Tail Type",
        "value": "Tail"
      },
      {
        "trait_type": "Headwear",
        "value": "Hat"
      },
      {
        "trait_type": "Mouth Accessories",
        "value": "Cigarette"
      },
      {
        "trait_type": "Eye Accessories",
        "value": "Mask"
      },
      {
        "trait_type": "Ear Accessories",
        "value": "Headphones"
      },
      {
        "trait_type": "Details",
        "value": "Headband"
      }
    ],
  },
{
    "name": "File2",
    "artist": "Andrew",
    "attributes": 
[
      {
        "trait_type": "Background",
        "value": "White"
      },
      {
        "trait_type": "Base",
        "value": "Black"
      },
      {
        "trait_type": "Eye Type",
        "value": "Eye"
      },
      {
        "trait_type": "Ear Type",
        "value": "Ear"
      },
      {
        "trait_type": "Tail Type",
        "value": "Tail"
      },
      {
        "trait_type": "Headwear",
        "value": "Hat"
      },
      {
        "trait_type": "Mouth Accessories",
        "value": "Cigarette"
      },
      {
        "trait_type": "Eye Accessories",
        "value": "Mask"
      },
      {
        "trait_type": "Ear Accessories",
        "value": "Headphones"
      },
      {
        "trait_type": "Details",
        "value": "Headband"
      }
    ],
  },

to

[
  {
    "Background": "Black",
    "Base": "White",
    "Eye Type": "Eye",
    "Ear Type": "Ear",
    "Tail Type": "Tail",
    "Headwear": "Hat",
    "Mouth Accessories": "Cigarette",
    "Eye Accessories": "Mask",
    "Ear Accessories": "Headphones",
    "Details": "Headband",
    "tokenId": 0
  },
  {
    "Background": "White",
    "Base": "Black",
    "Eye Type": "Eye",
    "Ear Type": "Ear",
    "Tail Type": "Tail",
    "Headwear": "Hat",
    "Mouth Accessories": "Cigarette",
    "Eye Accessories": "Mask",
    "Ear Accessories": "Headphones",
    "Details": "Headband",
    "tokenId": 1
  },
]

The first json file has a lot of data, I only put two examples in order not to create a code that is too long. In the new file, there are constants which are "Background", "Base"... and the last value which is "tokenId" which increases progressively.

Thank you very much.

Use this topic to code your script Is it possible to write data to file using only JavaScript? It's a simple array/object itération...

 const json = '[{"name":"File","artist":"Andrew","attributes":[{"trait_type":"Background","value":"Black"},{"trait_type":"Base","value":"White"},{"trait_type":"Eye Type","value":"Eye"},{"trait_type":"Ear Type","value":"Ear"},{"trait_type":"Tail Type","value":"Tail"},{"trait_type":"Headwear","value":"Hat"},{"trait_type":"Mouth Accessories","value":"Cigarette"},{"trait_type":"Eye Accessories","value":"Mask"},{"trait_type":"Ear Accessories","value":"Headphones"},{"trait_type":"Details","value":"Headband"}]},{"name":"File2","artist":"Andrew","attributes":[{"trait_type":"Background","value":"White"},{"trait_type":"Base","value":"Black"},{"trait_type":"Eye Type","value":"Eye"},{"trait_type":"Ear Type","value":"Ear"},{"trait_type":"Tail Type","value":"Tail"},{"trait_type":"Headwear","value":"Hat"},{"trait_type":"Mouth Accessories","value":"Cigarette"},{"trait_type":"Eye Accessories","value":"Mask"},{"trait_type":"Ear Accessories","value":"Headphones"},{"trait_type":"Details","value":"Headband"}]}]'; const result = JSON.parse(json).map((parent, i) => { const val = parent.attributes.reduce((prev, curr) => ({...prev, [curr.trait_type]: curr.value}), {}); val.tokenId = i; return val; }) console.log(JSON.stringify(result))

 const dat = [ {"name": "File", "artist": "Andrew", "attributes": [{"trait_type": "Background", "value": "Black"}, {"trait_type": "Base", "value": "White"}, {"trait_type": "Eye Type", "value": "Eye"}, {"trait_type": "Ear Type", "value": "Ear"}, {"trait_type": "Tail Type", "value": "Tail"}, {"trait_type": "Headwear", "value": "Hat"}, {"trait_type": "Mouth Accessories", "value": "Cigarette"}, {"trait_type": "Eye Accessories", "value": "Mask"}, {"trait_type": "Ear Accessories", "value": "Headphones"}, {"trait_type": "Details", "value": "Headband"}], }, {"name": "File2", "artist": "Andrew", "attributes": [{"trait_type": "Background", "value": "White"}, {"trait_type": "Base", "value": "Black"}, {"trait_type": "Eye Type", "value": "Eye"}, {"trait_type": "Ear Type", "value": "Ear"}, {"trait_type": "Tail Type", "value": "Tail"}, {"trait_type": "Headwear", "value": "Hat"}, {"trait_type": "Mouth Accessories", "value": "Cigarette"}, {"trait_type": "Eye Accessories", "value": "Mask"}, {"trait_type": "Ear Accessories", "value": "Headphones"}, {"trait_type": "Details", "value": "Headband"}] } ] const res = [] dat.forEach(d => { let obj = {} d.attributes.forEach(m => { obj[m['trait_type']] = m['value'] }) res.push(obj) }) console.log(res)

Keep in mind that JSON stands for JavaScript Object Notation. That means that any valid JSON is the stringified (or serialized) version of the JavaScript object. That means we can simply create an in memory object directly from the JSON string like so: (limited example to keep it small)

let origJson = {
    "name": "File",
    "artist": "Andrew",
    "attributes": 
  [
      {
        "trait_type": "Background",
        "value": "Black"
      }
  ]
}

Note, you need this first one to be an array of these so you really need to wrap your first JSON in an outer set of [ ] so you have an array of those that you can iterate over.

Like this...

let origJson = [{
    "name": "File",
    "artist": "Andrew",
    "attributes": 
  [
      {
        "trait_type": "Background",
        "value": "Black"
      }
  ]
},
{
//second object here...
},
{
// ... more objects 
},
]

Once you've done that you need a class that represents your 2nd object -- the one that you are mapping to. You'll need to complete the object to insure every property can be initialized -- it was too much typing for me. Also notice that you have some property names that have spaces & I've removed those spaces. Spaces won't work for property names. This NewObject class is just a representation of your second JSON example.

class NewObject
{
    constructor(Background, Base, EyeType, EarType, TailType,
    Headwear, MouthAccessories, EyeAccessories, EarAccessories,
    Details, tokenId)
    {
      this.Background =Background;
      this.Base = Base; 
      this.EyeType = ...
    }
}

Once you have that, you can now iterate through the first object creating new instances of the NewObject. Something like the following.

// set up a new array of NewObjects
let allNewObjects = [];
origJson.forEach((item) => {
    allNewObjects.push (new NewObject(item.attributes[0].value, item.attributes[1].value, ...));
    console.log(item.attributes[0].value, item.attributes[1].value);
});

Because I suggest the origJson be wrapped in outer [ ] it means that the loaded up variable origJson becomes an array of your original objects.

JavaScript arrays have a.forEach() method which will call a function for each item in the array -- passing each item in the array as an argument.

In my example I've implemented an arrow function that has two statements:

  1. that maps to the new object
  2. which outputs to the console.

Here's a fully working example:

 // define (minimal) target class class NewObject { constructor(Background, Base) { this.Background =Background; this.Base = Base; } } // load up your JSON into an array of objects let origJson = [{ "name": "File", "artist": "Andrew", "attributes": [ { "trait_type": "Background", "value": "Black" },{ "trait_type": "Base", "value": "White" }, ] }] // init array to hold all new objects let allNewObjects = []; // iterate over each original object and map to new origJson.forEach((item) => { allNewObjects.push (new NewObject(item.attributes[0].value, item.attributes[1].value)); console.log("attr 0: " + item.attributes[0].value, "attr 1: " + item.attributes[1].value); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM