简体   繁体   中英

Trying to read a json file in Python then add a certain value into an array

[OrderedDict([("{'asin': '0000037214'", "{'asin': '0000031887'"), (" 'related': {'also_viewed': ['B00JO8II76'", " 'related': {'also_bought': ['0000031852'"), (" 'B00DGN4R1Q'", " '0000031895'"), (" 'B00E1YRI4C']}", " '0000031909'"), (" 'title': 'Purple Sequin Tiny Dancer Tutu Ballet Dance Fairy Princess Costume Accessory'", " 'B00D2K1M3O'"), (" 'price': 6.99", " 'B00D10CLVW'"), (" 'salesRank': {'Clothing': 1233557}", " 'B003AVKOP2'"), (" 'imUrl': ' http://ecx.images-amazon.com/images/I/31mCncNuAZL.jpg '", " 'B00D103F8U'"), (" 'brand': 'Big Dreams'", " 'B00613WDTQ'"), (" 'categories': [['Clothing", " 'B008F0SU0Y'"), (" Shoes & Jewelry'", " 'B008UBQZKU'"), (" 'Girls']", " 'B00D0GCI8S'"), (" ['Clothing", " 'B00E1YRI4C'"), (" 'Novelty", " 'B003AVEU6G'"), (" Costumes & More'", " 'B008F0SMUC'"), (" 'Costumes & Accessories'", " 'B002C3Y6WG'"),

So in a python file, I would want to parse over this json file^^^ line by line and when it gets the ID part I want it to add the value of it to a list. I just don't want to print out all the individual values I want to append all the ids values into a list. So by at the end, I should have a list containing 1 and 2

clothing_ids = [1,2]

Like so ^^, Below is what I have tried so far but can't seem to get to work.

clothing_ids = {'List of Clothing IDs': []}

json_file = open('jsonfile.json', 'r') 
file = json_file.read()
for line in file:
    if 'id' in line:
        clothing_ids['List of Clothing IDs'].append(this)
 print(data)
 json_file.close()

***IDs in this file are called 'asin'

clothing_ids = []    
for key, value in file.items():
    if key == 'id':
        clothing_ids.append(value)

Go through every key value pair, and where the key is ID, add the value to your ID list.

If your JSON file was syntactically correct and contained an array of those objects, you could just use the JSON parsing library:

import json
data = json.load(open('jsonfile.json'))
clothing_ids = {'List of Clothing IDs': map(lambda x: x['ID'], data)}

That worked on this JSON file:

[
  {
    "ID": "1",
    "FirstName": "John",
    "LastName": "Smith",
    "Age": 27
  },
  {
    "ID": "2",
    "FirstName": "Frank",
    "LastName": "Jones",
    "Age": 29
  }
]

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