Open the file with any text editor. Add a [ at the very beginning of the file, and a ] at the very end. This will transform the data you have into an actual valid JSON array.
Then use the json module to work with it.
(EDITED CORRECTED VERSION BASED ON COMMENTS, thx @martin-novosad)
import json
with open("example.json") as f:
arr = json.load(f)
# Do nifty stuff with resulting array.
Answer from FrobberOfBits on Stack OverflowVideos
You should be able to condense the whole thing down to just this:
import json
tables = ["a", "b", "c", "d"]
data = {}
for t in tables:
results = sf.query("select id from %s" % t)["records"]
data[t] = [r["id"] for r in results]
with open("Dataset.json", "w") as f:
json.dump(data, f)
You can simply create a dictionary containing the values you are after and then convert it to json using json.dumps
import json
data = {}
data['a'] = ["12","34","23"]
data['b'] = ["13","14","45"]
json_data = json.dumps(data)
print json_data
You're trying to read the string "data.txt". What you want is to open and read the file.
import json
with open('data.txt', 'r') as data_file:
json_data = data_file.read()
data = json.loads(json_data)
Try:
data = json.load(open("data.txt", 'r'))
json.loads interprets a string as JSON data, while json.load takes a file object and reads it, then interprets it as JSON.
The error message is correct.
key = json.loads(response['password'])
print(key[0]),
The format of json is string. You need to convert the string of a json object to python dict before you can access it.
i.e.: loads(string) before info[key]
key = json.loads(response)['password']
print(key[0])
Usually the json will be a string and you will try and deserialise it into a object graph (which in python are typically are made up of maps and arrays).
so assuming your response is actually a string (eg that was retrieved from a HTTP request/endpoint) then you deserialise it with json.loads (the function is basically load from string), then you've got a map with a 'password' key, that is an array, so grab the first element from it.
import json
resp = '{ "password": [ "Ensure that this field has atleast 5 and atmost 50 characters" ] }'
print json.loads(resp)['password'][0]
In your for loop statement, Each item in json_array is a dictionary and the dictionary does not have a key store_details. So I modified the program a little bit
import json
input_file = open ('stores-small.json')
json_array = json.load(input_file)
store_list = []
for item in json_array:
store_details = {"name":None, "city":None}
store_details['name'] = item['name']
store_details['city'] = item['city']
store_list.append(store_details)
print(store_list)
If you arrived at this question simply looking for a way to read a json file into memory, then use the built-in json module.
with open(file_path, 'r') as f:
data = json.load(f)
If you have a json string in memory that needs to be parsed, use json.loads() instead:
data = json.loads(my_json_string)
Either way, now data is converted into a Python data structure (list/dictionary) that may be (deeply) nested and you'll need Python methods to manipulate it.
If you arrived here looking for ways to get values under several keys as in the OP, then the question is about looping over a Python data structure. For a not-so-deeply-nested data structure, the most readable (and possibly the fastest) way is a list / dict comprehension. For example, for the requirement in the OP, a list comprehension does the job.
store_list = [{'name': item['name'], 'city': item['city']} for item in json_array]
# [{'name': 'Mall of America', 'city': 'Bloomington'}, {'name': 'Tempe Marketplace', 'city': 'Tempe'}]
Other types of common data manipulation:
For a nested list where each sub-list is a list of items in the
json_array.store_list = [[item['name'], item['city']] for item in json_array] # [['Mall of America', 'Bloomington'], ['Tempe Marketplace', 'Tempe']]For a dictionary of lists where each key-value pair is a category-values in the
json_array.store_data = {'name': [], 'city': []} for item in json_array: store_data['name'].append(item['name']) store_data['city'].append(item['city']) # {'name': ['Mall of America', 'Tempe Marketplace'], 'city': ['Bloomington', 'Tempe']}For a "transposed" nested list where each sub-list is a "category" in
json_array.store_list = list(store_data.values()) # [['Mall of America', 'Tempe Marketplace'], ['Bloomington', 'Tempe']]
The json.load() method (without "s" in "load") can read a file directly:
import json
with open('strings.json') as f:
d = json.load(f)
print(d)
You were using the json.loads() method, which is used for string arguments only.
The error you get with json.loads is a totally different problem. In that case, there is some invalid JSON content in that file. For that, I would recommend running the file through a JSON validator.
There are also solutions for fixing JSON like for example How do I automatically fix an invalid JSON string?.
Here is a copy of code which works fine for me,
import json
with open("test.json") as json_file:
json_data = json.load(json_file)
print(json_data)
with the data
{
"a": [1,3,"asdf",true],
"b": {
"Hello": "world"
}
}
You may want to wrap your json.load line with a try catch, because invalid JSON will cause a stacktrace error message.