The brackets denote a JSON array, containing one element in your example. In Python, simply pick out the first element of the root array and convert back to JSON.
import json
data = json.loads('[...]')
str = json.dumps(data[0])
Answer from Vortico on Stack OverflowThe brackets denote a JSON array, containing one element in your example. In Python, simply pick out the first element of the root array and convert back to JSON.
import json
data = json.loads('[...]')
str = json.dumps(data[0])
Just serialize the dictionary:
result = {"MetaData": {}, "SRData": dResult}
print(json.dumps(result, sort_keys=True, indent=4))
Hello guys, I am working on a weather app and this is my first time building a project using Flask and calling APIs. I am trying to get the weather description but it returns like this:
['Partly Cloudy']
How do I remove the square brackets and quotation sign?
So I have this:
response = urllib.request.urlopen(url)
raw_json = json.loads(response.read()) pinventory = json.dumps(raw_json)
I want remove all square brackets and regular brackets from pinventory. This is the url I'm getting the JSON from. https://steamcommunity.com/profiles/76561198345216182/inventory/json/440/2 It would be way easier to parse without the brackets, because they really mess with RegEx. Is there some way to either remove all the square and regular brackets or replace them with whitespace?
why?
the whole point of the json format is that once you parse it you can easily access whatever info you need.
what info do you need?
remove all square brackets and regular brackets
pinventory.translate({ord(k): '' for k in '[]{}'}) should work, but I think you don't need to remove brackets from the JSON as others saying. Note that json.loads() parses a raw JSON string and return a Python object (in this case, a dict). Thus you can write, for example:
parsed = json.loads(response.read())
for id_, rec in parsed['rgInventory'].items():
print( rec['classid'], rec['instanceid'])
If there's always exactly one "extra" set of array brackets:
for result in page['blah']:
that = result[0]['this']
list.append(that)
There is not need to remove the brackets from the JSON string. I think making sure to remove only the rights is not worth the effort. Just figure out the right way to access the values you want.
The "extra" brackets are not the only problem. this is a property of an object which is the value of first. So to access this, you'd have to write
that = result[0]['first']['this']
Whether this always works or not depends on the left-out JSON data.
You don't need to "remove" anything. You have a dictionary, each of whose values is a list. Calling str on a list will show the repr of the elements in it. If you don't want that, print the elements of the list:
for item in data:
print ', '.join(item['brand'])
Since the value for each'brand'key in each dictionary is alistobject, you need to do index into it something like this -- which prints the first element in each of these lists:
data = [{u'brand': [u'ABARTH']},
{u'brand': [u'ALFA ROMEO']},
{u'brand': [u'FORD']}]
for item in data:
print item['brand'][0].lower().replace(' ', '-')
Output:
abarth
alfa-romeo
ford
I've noticed that using indent in json.dumps, add new lines inside the lists (inside square brackets)
{
"mylist":[
1,
2,
3,
],
"who": "me"
}while i wanted something like this
{
"mylist": [1,2,3]
"who": "me"
}I tried to solve it using regex, but i cant figure it out. I tried to split the problem so
-
i want to display everything inside the square brackets
\[(.*?)\] -
i want to capture all new lines
(\r\n|\r|\n)
So i thought that writing something like re.sub("\[(\r\n|\r|\n)\]","", myjson) would have worked but nope.
any ideas?
Use this when you return:
return properties[0];
Or
var data = [
{
"Name": "TEST",
"deviceId": "",
"CartId": "",
"timestamp": 1383197265540,
"FOOD": [],
"City": "LONDON CA"
}
]; // Or whatever the Json is
data = data[0];
Or if you're accessing the json via another object
var data = jsonObj[0];
var tmpStr = '[
{
"Name": "TEST",
"deviceId": "",
"CartId": "",
"timestamp": 1383197265540,
"FOOD": [],
"City": "LONDON CA"
}
]';
var newStr = tmpStr.substring(1, tmpStr.length-1);
See this codepen example
You can load the json into a python object, and then convert the python object to YAML. The other solution is to simply iterate over the dictionaries and format it however you want.
Here's an example of converting it to YAML. It doesn't give you precisely what you want, but it's pretty close. There are lots of ways to customize the output, this is just a quick hack to show the general idea:
import json
import yaml
data = json.loads('''
{
"A": {
"A1": 1,
"A2": 2
},
"B": {
"B1": {
"B11": {
"B111": 1,
"B112": 2
},
"B12": {
"B121": 1,
"B122": 2
}
},
"B2": {
"B21": [1,2],
"B22": [1,2]
}
},
"C": "CC"
}
''')
print yaml.safe_dump(data, allow_unicode=True, default_flow_style=False)
This is the output I get:
A:
A1: 1
A2: 2
B:
B1:
B11:
B111: 1
B112: 2
B12:
B121: 1
B122: 2
B2:
B21:
- 1
- 2
B22:
- 1
- 2
C: CC
And if by chance you want it in your originally specified format, you can overload the pyyaml class structure to customize as desired:
Code:
import yaml
from yaml.emitter import Emitter
from yaml.serializer import Serializer
from yaml.representer import Representer
from yaml.resolver import Resolver
class MyRepresenter(Representer):
def represent_sequence(self, tag, sequence, flow_style=None):
value = []
node = yaml.SequenceNode(tag, value, flow_style=flow_style)
if self.alias_key is not None:
self.represented_objects[self.alias_key] = node
best_style = True
for item in sequence:
node_item = self.represent_data(item)
if not (isinstance(node_item, yaml.ScalarNode) and
not node_item.style):
best_style = False
value.append(node_item)
if best_style:
node = self.represent_data(
str(', '.join('%s' % x.value for x in value)))
if flow_style is None:
if self.default_flow_style is not None:
node.flow_style = self.default_flow_style
else:
node.flow_style = best_style
return node
class MyDumper(Emitter, Serializer, MyRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None):
Emitter.__init__(self, stream, canonical=canonical,
indent=indent, width=width,
allow_unicode=allow_unicode, line_break=line_break)
Serializer.__init__(self, encoding=encoding,
explicit_start=explicit_start, explicit_end=explicit_end,
version=version, tags=tags)
MyRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
print yaml.dump(data, Dumper=MyDumper, default_flow_style=False)
Produces:
A:
A1: 1
A2: 2
B:
B1:
B11:
B111: 1
B112: 2
B12:
B121: 1
B122: 2
B2:
B21: 1, 2
B22: 1, 2
C: CC