-1

I am a fairly new dev and trying to parse "id" values from this file. Running into the issue below.

My python code:

import ast
from pathlib import Path

file = Path.home() /'AppData'/'Roaming'/'user-preferences-prod'

with open(file, 'r') as f:
    contents = f.read()
    ids = ast.literal_eval(contents)
profileids = []
for data in ids:
    test= data.get('id')
    profileids.append(test)
print(profileids))

This returns the error: ValueError: malformed node or string: <_ast.Name object at 0x0000023D8DA4D2E8> at ids = ast.literal_eval(contents)

A snippet of the content in my file of interest:

{"settings":{"defaults":{"value1":,"value2":,"value3":null,"value4":null,"proxyid":null,"sites":{},"sizes":[],"value5":false},"value6":true,"value11":,"user":{"value9":"","value8": ,"value7":"","value10":""},"webhook":"},'profiles':[{'billing': {'address1': '', 'address2': '', 'city': '', 'country': 'United States', 'firstName': '', 'lastName': '', 'phone': '', 'postalCode': '', 'province': '', 'usesBillingInformation': False}, 'createdAt': 123231231213212, 'id': '23123123123213, 'name': ''

I need this code to be looped as there are multiple id values that I am interested in and need them all to be entered into a list.Hopefully I explained it all. the file type is "file" according to windows, I just view its contents with notepad.

Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56

1 Answers1

0

It appears to me that you have a file with a string representation of a dict (dictionary). So, what you need to do is:

string_of_dictast.literal_eval()dict

  1. Open file and read in the text into a string variable. Currently I think this string is going into ids.
  2. Then convert the string representation of dict into a dict using ast library as shown below. Reference
import ast
string_of_dict = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
ast.literal_eval(string_of_dict)

Output:

{'muffin': 'lolz', 'foo': 'kitty'}

Solution

Something like this should most likely work. You may have to tweak it a little bit.

import ast

with open(file, 'r') as f:
    contents = f.read()
ids = ast.literal_eval(contents)
profileids = []
for data in ids:
    test= data.get('id')
    profileids.append(test)
print(profileids)
CypherX
  • 7,019
  • 3
  • 25
  • 37
  • Thanks! This returns this error tho: ValueError: malformed node or string: <_ast.Name object at 0x000001ADCC357550> – cryptopharoh Sep 17 '19 at 03:32
  • Also share some part of your file so we could figure out if it is a formatted as a dict or something else. You would need to share from the beginning of your file. – CypherX Sep 17 '19 at 03:51
  • Have adjusted the initial post with your requested info. though i replaced the real key name and removed the values for security. – cryptopharoh Sep 17 '19 at 12:27