Converting JSON String to Dictionary Not List

Converting JSON String to Dictionary Not List

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

How convert a JSON string to Dictionary in Python?

Surround your original string with square brackets to make it a valid JSON string:

import json

valid_json_string = "[" + your_string + "]" # or "[{0}]".format(your_string)
data = json.loads(valid_json_string)

How to convert a JSON string to a dictionary?

Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.

Swift 3

func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}

let str = "{\"name\":\"James\"}"

let dict = convertToDictionary(text: str)

Swift 2

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}

let str = "{\"name\":\"James\"}"

let result = convertStringToDictionary(str)

Original Swift 1 answer:

func convertStringToDictionary(text: String) -> [String:String]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
if error != nil {
println(error)
}
return json
}
return nil
}

let str = "{\"name\":\"James\"}"

let result = convertStringToDictionary(str) // ["name": "James"]

if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
println(name) // "James"
}

In your version, you didn't pass the proper parameters to NSJSONSerialization and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:

let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]

and of course you would also need to change the return type of the function:

func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }

How can I deserialize JSON to a simple Dictionarystring,string in ASP.NET?

Json.NET does this...

string json = @"{""key1"":""value1"",""key2"":""value2""}";

var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

More examples: Serializing Collections with Json.NET

Convert JSON string to dict using Python

json.loads()

import json

d = json.loads(j)
print d['glossary']['title']

json.loads function not giving python dictionary

The json string that you are trying to convert is not properly formatted. Also, you need to only call json.loads to convert string into dict or list.

The updated code would look like:

import json
a = '[{"id": 35, "name": "Comedy"}, {"id": 18, "name": "Drama"}, {"id": 10751, "name": "Family"}, {"id": 10749, "name": "Romance"}]'
b = json.loads(a)
print(type(b))

Hope this explains why you are not getting the expected results.

Convert json strings to a single dictionary in python

Try this,

import json

d = {}
with open('file1.txt') as f:
for line in f:
data = json.loads(line)
for k, v in data.items():
d.setdefault(k,[]).append(v)

or you can use defaultdict to define empty dict with values as list.

import json
from collections import defaultdict

d = defaultdict(list)
with open('file1.txt') as f:
for line in f:
data = json.loads(line)
for k, v in data.items():
d[k].append(v)

Output:

print(d)

{'_id': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'name': ['aimee Zank', 'Aurelia Menendez', 'Corliss Zuk', 'Bao Ziglar', 'Zachary Langlais', 'Wilburn Spiess', 'Jenette Flanders', 'Salena Olmos', 'Daphne Zheng', 'Sanda Ryba'], 'scores': [[{'score': 1.463179736705023, 'type': 'exam'}, {'score': 11.78273309957772, 'type': 'quiz'}, {'score': 35.8740349954354, 'type': 'homework'}], [{'score': 60.06045071030959, 'type': 'exam'}, {'score': 52.79790691903873, 'type': 'quiz'}, {'score': 71.76133439165544, 'type': 'homework'}], [{'score': 67.03077096065002, 'type': 'exam'}, {'score': 6.301851677835235, 'type': 'quiz'}, {'score': 66.28344683278382, 'type': 'homework'}], [{'score': 71.64343899778332, 'type': 'exam'}, {'score': 24.80221293650313, 'type': 'quiz'}, {'score': 42.26147058804812, 'type': 'homework'}], [{'score': 78.68385091304332, 'type': 'exam'}, {'score': 90.2963101368042, 'type': 'quiz'}, {'score': 34.41620148042529, 'type': 'homework'}], [{'score': 44.87186330181261, 'type': 'exam'}, {'score': 25.72395114668016, 'type': 'quiz'}, {'score': 63.42288310628662, 'type': 'homework'}], [{'score': 37.32285459166097, 'type': 'exam'}, {'score': 28.32634976913737, 'type': 'quiz'}, {'score': 81.57115318686338, 'type': 'homework'}], [{'score': 90.37826509157176, 'type': 'exam'}, {'score': 42.48780666956811, 'type': 'quiz'}, {'score': 96.52986171633331, 'type': 'homework'}], [{'score': 22.13583712862635, 'type': 'exam'}, {'score': 14.63969941335069, 'type': 'quiz'}, {'score': 75.94123677556644, 'type': 'homework'}], [{'score': 97.00509953654694, 'type': 'exam'}, {'score': 97.80449632538915, 'type': 'quiz'}, {'score': 25.27368532432955, 'type': 'homework'}]]}

Trying to deserialize JSON into Dictionarystring, Liststring in c#

Solution As Per Question:

Try this, Hopefully this will help you. https://dotnetfiddle.net/f3u1TC

string json = @"[{""key1"":[""value1.1"",""value1.2""]},{""key2"":[""value2.1"",""value2.2""]}]";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>[]>(json);

Edit

Updated Solution:

If you don't need an array. Then you have to update your json. Remove array braces [] and add these ones {}

Json

{
{
"key1": [
"value1.1",
"value1.2"
]
},
{
"key2": [
"value2.1",
"value2.2"
]
},
}

C#

string json = @"{""key1"":[""value1.1"",""value1.2""],""key2"":[""value2.1"",""value2.2""]}";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);

Python convert string holding nested json to dict

Your nested key seems like a JSON string that can be loaded into a dictionary using json.loads method.
Though the nested JSON won't get converted to the dictionary that's why I've added the recursive function to address the nested dictionary present in the JSON.

import json
from json import JSONDecodeError

def recurse(d):
try:
if isinstance(d, dict):
loaded_d = d
else:
loaded_d = json.loads(d)
for k, v in loaded_d.items():
loaded_d[k] = recurse(v)
except (JSONDecodeError, TypeError):
return d
return loaded_d

for d in data_list:
for key, val in d.items():
d[key] = recurse(val)

Output:

[
{
"keyA": "Example",
"keyB": {"keyC": 2, "keyD": {"keyE": {"name": "foo"}}, "keyF": 0},
},
{
"keyA": "Example2",
"keyB": {"keyC": 6, "keyD": {"keyE": {"name": "bar"}}, "keyF": 5},
},
]


Related Topics



Leave a reply



Submit