1

Have a json contain list of dictionaries as following:

[
  {
    "native_data": {
      "PopOrGuess": null,
      "role": "D",
      "TSX": "Included"
    },
    "id": "3dsdsa_a_12sss"
  },
  {
    "native_data": {
      "PopOrGuess": 123,
      "role": "A",
      "TSX": "NA"
    },
    "id": "12_123_saba"
  }
]

I need to extract this list and create new json file per element in list, so file_name will get the "id" value ,and the json content the first element in dict, meaning for first element "id": "12_123_saba" file name: 3dsdsa_a_12sss.json

{
    "native_data": {
      "PopOrGuess": null,
      "role": "D",
      "TSX": "Included"
    }
  }

I tried :

def ExtractJsonPrice( file ):
    jsonFile = open(file, "r") # Open the JSON file for reading
    try:
       json_data = json.load(jsonFile)
    except ValueError:
           print("error loading JSON")
           logging.error("Exception occurred", exc_info=True)
    
    for item in json_data:
        file_name = item['id']
        json_content = item['native_data'] 

and from there i have the file name , but the problem , the json_content holds now the content of the key of 'native_data' but it actually missing the KEY "native_data", I guess I could append it as post process but im sure there's more efficient way.

2 Answers 2

2

yes you are getting the key, you can do this,

json_content = {'native_data': item['native_data']}
Sign up to request clarification or add additional context in comments.

Comments

1

Found a way:

    
    for item in json_data:
        json_content = {}
        file_name = item['id']
        json_content["native_data"]= item['native_data'] 
        file_name = list(item.values())[1]
        
        with open('ID_' + file_name + '.json' , 'w') as fp:  
             json.dump(json_content,fp)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.